I'm writing a blogging system. Now I'm working on comments for posts. Here is the schema for every single post:
{
"topic": "Post Topic",
"post": "<p>\r\n\tPost text</p>\r\n",
"time_added": 1343167025,
"author": "Ashley Brooks",
"_id": {
"$oid": "500f1a315759c73805000001"
}
}
Now, I'd like to add a comment for this post. I suppose the best way of storing comments is smth like:
{
"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"
}
]
}
I've read some docs for Mongo, however I could'n find a proper way of adding new comments. This is how I'm doing now:
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('/');
}
};
It returns me such error:
exception: must specify remove or update
What I'm doing wrong?
P.S. BTW, I think it would be nice to mark separate comments with any unique id or smth like that. How can I specify Mongo to add an obj_id parameter for every adding comment? Thanks in advance.
Used 'update' and it worked:
collection.update(
{_id: obj_id}, // query
{$push: {
comments: {comment: req.body.comment, name: "testname" }
}
},