【问题标题】:How to use mongoose update, and update a embed document?如何使用猫鼬更新,并更新嵌入文档?
【发布时间】:2012-04-16 21:35:02
【问题描述】:

我已经阅读了猫鼬文档,但我仍然不知道如何更新文档。

我在 mongoose 中使用 node、express 和 mongodb。

这是我的 mongodb 中的一个集合...

{ "title" : "this is a title",
    "_id" : ObjectId( "4f7a92554ad893f322000004" ),
  "nodes" : [ 
               { "title" : "this is node 1",
                   "_id" : ObjectId( "4f7a92554ad893f322000009" ) }, 
               { "title" : "this is node 2",
                   "_id" : ObjectId( "4f7a92554ad893f322000008" ) }, 
               { "title" : "this is node 3",
                   "_id" : ObjectId( "4f7a92554ad893f322000007" ) }, 
               { "title" : "this is node 4",
                   "_id" : ObjectId( "4f7a92554ad893f322000006" ) }, 
               { "title" : "this is node 5",
                   "_id" : ObjectId( "4f7a92554ad893f322000005" ) }
            ]
}

如何更新节点嵌入文档???

app.put('/api/paper/:pid/:nid', function(req, res) {
    var PaperModel = mongoose.model('papers', Paper);
    PaperModel.update({_id: req.params.pid, 'nodes._id': req.params.nid}, {title: 'this         is a new node title'}, function(error, result) {
        console.dir(result);
    });
});

它不工作。

如何更新嵌入数组“节点”

nodes._id: 4f7a92554ad893f322000009 标题:这是节点 1 到标题:这是一个新标题?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:
    PaperModel.update(
        {_id: req.params.pid, 'nodes._id': req.params.nid}
      , { $set: {'nodes.$.title': 'this is a new node title'}}
      , function(error, result) {
          console.dir(result);
        }
    );
    

    请注意,这一次只能更新一个子文档(mongodb 限制)。

    【讨论】:

      猜你喜欢
      • 2011-10-25
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2012-05-11
      • 2016-05-24
      • 2012-02-15
      • 2015-04-21
      相关资源
      最近更新 更多