1
我在写博客系统。现在我正在处理帖子的评论。这里是每一个岗位的模式:Node + Mongo:向集合中的数组添加记录
{
"topic": "Post Topic",
"post": "<p>\r\n\tPost text</p>\r\n",
"time_added": 1343167025,
"author": "Ashley Brooks",
"_id": {
"$oid": "500f1a315759c73805000001"
}
}现在
,我想添加评论这个职位。我想存储评论的最好的办法是水木清华这样的:
{
"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"
}
]
}
我读过的一些蒙戈文档,但是我could'n发现添加新评论的正确方法。这就是我现在所做的:
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
我做错了吗?
P.S.顺便说一句,我认为用任何独特的ID标记单独的评论或者像这样的评论会很好。我如何指定Mongo为每个添加注释添加obj_id参数?提前致谢。