【问题标题】:Node + Mongo: adding record to array inside collectionNode + Mongo:将记录添加到集合内的数组
【发布时间】:2012-07-24 22:07:31
【问题描述】:

我正在编写一个博客系统。现在我正在研究 cmets 的帖子。这是每个帖子的架构:

{
"topic": "Post Topic",
"post": "<p>\r\n\tPost text</p>\r\n",
"time_added": 1343167025,
"author": "Ashley Brooks",
"_id": {
    "$oid": "500f1a315759c73805000001"
}

}

现在,我想为这篇文章添加评论。我想存储 cmets 的最佳方式是:

{
"topic": "Post Topic",
"post": "<p>\r\n\tPost text</p>\r\n",
"time_added": 1343167025,
"author": "Ashley Brooks",
"_id": {
    "$oid": "500f1a315759c73805000001"
},
"comments" : [
    {
        "author":"James Brown",
        "comment":"My awesome comment"
    },
    {
        "author":"Jimmy White",
        "comment":"And this is my comment"
    }
]
}

我已经阅读了一些有关 Mongo 的文档,但是我找不到添加新 cmets 的正确方法。这就是我现在的做法:

exports.post = function(req, res) {
if (req.currentUser) {
    db.collection("posts", function (err, collection) {
        var obj_id = BSON.ObjectID.createFromHexString(req.params.id);
        console.log(obj_id);
        collection.findAndModify(
            {_id: obj_id}, // query for a post
            {$push: {
                comments: [ {author: req.body.comment, name: "testname" } ]
                }
            },
            function(err, object) {
                if (err){
                    console.warn(err.message);
                }else{
                    res.redirect('/');
                }
            });
    });
} else {
    res.redirect('/');
}

};

它返回给我这样的错误:

exception: must specify remove or update

我做错了什么?

附:顺便说一句,我认为用任何唯一的 id 或类似的 smth 标记单独的 cmets 会很好。如何指定 Mongo 为每个添加评论添加 obj_id 参数?提前致谢。

【问题讨论】:

    标签: arrays node.js mongodb collections


    【解决方案1】:

    使用了“更新”并且成功了:

    collection.update(
                {_id: obj_id}, // query
                {$push: {
                    comments: {comment: req.body.comment, name: "testname" }
                    }
    
                },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      相关资源
      最近更新 更多