Skip to content
This repository has been archived by the owner on Jun 11, 2021. It is now read-only.

Update using upsert #65

Open
shivagarwal opened this issue Jan 27, 2012 · 5 comments
Open

Update using upsert #65

shivagarwal opened this issue Jan 27, 2012 · 5 comments

Comments

@shivagarwal
Copy link

Updating a document using upsert only creates a new record but when try to save the same document with an updated key value it creates a new record altogether instead of updating the existing document as it should with "upsert"

For example:

class User extends Shanty_Mongo_Document
{
protected static $_db = 'forum';
protected static $_collection = 'user';

protected static $_requirements = array(
    'name' => 'Required',
    'email' => array('Required', 'Validator:EmailAddress'),
    'friends' => 'DocumentSet',
    'friends.$' => array('Document:User', 'AsReference')
);

}

Now if you want to add or update a record based ont he criteria that email exists

$usr = new User();
//set up the values for user
$usr->update(array('email' => '[email protected]', array('$set' => $usr->export()),array('upsert' => true));

the above should either create a new User document if the email does not exist or update and existing one combining the criteria and the update.

It successfully creates a new record on the first save but on the second save it creates a new record instead of updating the existing one.

@tbjers
Copy link

tbjers commented Feb 1, 2012

From your code you have already explicitly created a new document in $usr = new User(). I think an upsert should be called statically on the User object, like so: User::upsert($usr->export()). At least that makes more sense to me.

@shivagarwal
Copy link
Author

I created the User object to get an export of the User array and tried calling update statically but still have the same issue

@tbjers
Copy link

tbjers commented Feb 1, 2012

Couldn't you do something like this:

$user = new User();
$result = $user->_getMongoCollection(true)->update(array('username' => 'example'), array('email' => '[email protected]'), array('upsert' => true));

That should work since it's using the native PHP MongoDB extension MongoCollection::update AFAIK.

This would look for the user with the username "example," and if not found, it would simply create that user...

@shivagarwal
Copy link
Author

Yes, that should work but I have used the native PHP MongoDB extension anyways

@tbjers
Copy link

tbjers commented Feb 1, 2012

CORRECTION: use User::getMongoCollection(true) instead of creating a new User() object.

I have verified that using User::getMongoCollection(true)->update(...) works as intended.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants