簡體   English   中英

如何使用Node.JS Driver在mongodb中保存修改后的對象

[英]How to save a modified object in mongodb using Node.JS Driver

我想在MongoDB中查找,修改並保存對象。 它看起來像這樣:

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
    }
  });
});

我現在如何保存對數據庫所做的更改?

或者我應該使用.update()? 這里的問題是,我不想交換整個對象,但更多的東西插入到該對象的數組中。

謝謝和最好,馬克

db.collection.update ({'facebook_id':req.params.facebook_id}, item, function (err) {
    if (err) return next (err);
});
collection.update({'facebook_id':req.params.facebook_id}, 
  {$push: { messages: {'value': message.value, 'date': message.date} } }, function(err) {

});

使用$ push運算符直接在數據庫中向數組添加值。 http://docs.mongodb.org/manual/reference/operator/update/push/

請注意,這比更新整個對象更有效,特別是對於大對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM