I want to find, modify and afterwards save an object in MongoDB. It looks like that:
var message = req.body;
db.collection('user', function(err, collection) {
collection.findOne({'facebook_id':req.params.facebook_id}, function(err, item) {
if(item) {
item.messages.push({'value': message.value, 'date': message.date});
//save Object
}
});
});
How can I now save the changes I made to the database?
Or should I instead use .update()? The problem here is, that I don't want to swap the whole object, but much more insert something into an array of that object.
Thanks & Best, Marc
collection.update({'facebook_id':req.params.facebook_id},
{$push: { messages: {'value': message.value, 'date': message.date} } }, function(err) {
});
Use the $push operator to add a value to an array directly in the database. http://docs.mongodb.org/manual/reference/operator/update/push/
Note that this is much more efficient than updating the entire object, especially for large objects.