amark / mongous

Simple MongoDB driver for Node.js with jQuery like syntax.
MIT License
246 stars 30 forks source link

Save not updating? #7

Closed xjamundx closed 13 years ago

xjamundx commented 13 years ago

I'm trying to use .save() to update some existing records and it doesn't appear to work, though the function itself returns true. Any thoughts?

There is an existing user in the database that looks like this:

{name: 'GitHub User'
   , phone: '801-555-5555'
   , email: 'github@i.tv'
   , position: 'sr. gitmaster'
   , twitter: 'github'
   , pic: 'https://github.com/images/gravatars/gravatar-140.png'
   , yearsEmployed: '0'
   , _id: 'github-user-1299185222151'
}

I want to add an @ in front of of his twitter name, so I try this with no luck:

mongous("mydb.users").save({name: 'GitHub User'
    , phone: '801-555-5555'
    , email: 'github@i.tv'
    , position: 'sr. gitmaster'
    , twitter: '@github'
    , pic: 'https://github.com/images/gravatars/gravatar-140.png'
    , yearsEmployed: '0'
    , _id: 'github-user-1299185222151'
});

This doesn't seem to work, but from command line Mongo can do and it does update:

db.users.save({name: 'GitHub User'
    , phone: '801-555-5555'
    , email: 'github@i.tv'
    , position: 'sr. gitmaster'
    , twitter: '@github'
    , pic: 'https://github.com/images/gravatars/gravatar-140.png'
    , yearsEmployed: '0'
    , _id: 'github-user-1299185222151'
});

Oh and I just figured out that this works as an alternative:

mongous("mydb.users").update({_id:user._id}, user); 
amark commented 13 years ago

correct. you need to use the update command. according to http://try.mongodb.org/ save() does not work as you've shown. I'd love for it to work that way, but it just isn't how mongodb is designed. save() works like this: {name:'joe'} exists? (no) add it. (yes) replace it. unfortunately it is the entire object that is matched, not individual attributes. so you can't add new attributes or else it adds it as a new object.

To update something, use update. The first object has the attributes you are looking for, while the second object is what you want to replace it with. WARNING: according to Mongo, the second object replaces the entire object.

to do this please use '$set' attribute with its value as an object itself.

please read mongo docs and mongous docs. thanks! :) ...I wish save would work like that too! But it doesn't.

xjamundx commented 13 years ago

Thanks for the information! This is a great project.