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參數?提前致謝。