0

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

Luxori
  • 115
  • 7

2 Answers2

1
db.collection.update ({'facebook_id':req.params.facebook_id}, item, function (err) {
    if (err) return next (err);
});
JuJoDi
  • 14,627
  • 23
  • 80
  • 126
  • Thank you for your answer. So I call .update in the callback of .findeOne(). Could you explain in a few words what `if (err) return next (err);` does? – Luxori Apr 29 '14 at 14:56
  • There is a callback passed to all middleware of an express application that is frequently called "next". It's not really relevant to this question. You can do whatever you want with the error – JuJoDi Apr 29 '14 at 15:04
1
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.

Will Shaver
  • 12,471
  • 5
  • 49
  • 64
  • Thanks! That sounds efficient. Could you also tell me how to do that, if the modified array itself is in another array? Let's say: `user.circles[j].messages.push(message)`. (I already know j). – Luxori Apr 29 '14 at 15:21