I am trying to remove an array element from a MongoDB collection in Node.js. The problem is, that although the callback returns 1
and its error is null
which should indicate that the operation was successful, right? But when I check the database, the element I wanted to delete is still there. If I execute the same command in the Mongo Shell it works. I really don't see what I am doing wrong. Does anyone have an idea?
My object in the collection:
{
"_id" : ObjectId("55dc82bd0ab9de6c20bc2eb9"),
"title" : "post title",
"content": "post content",
"time" : 1440514750,
"comments" : [
{
"time" : 1440683176,
"username" : "arne",
"content" : "This is my comment"
},
{
"time" : 1440683198,
"username" : "jack",
"content" : "This is another comment"
}
]
}
Working command in mongo shell (successfully removes comment from collection):
> db.posts.update({_id: ObjectId("55dc82bd0ab9de6c20bc2eb9")}, {$pull: {comments: {time: 1440683198}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Not working function in node.js:
req.db.collection('posts').update({_id: new mongoID(postId)}, {$pull: {comments: {time: commentTime}}}, function(err, result) {
console.log('result', result);
console.log('err', err);
res.redirect('/blog/' + postId);
});
Output:
object 1
err null
but the comment I wanted to delete is still there