Mongoose - removes elements from the DBref array and the element itself

I have a circuit that looks something like this:

var postSchema = new Schema({ created: { type: Date, default: Date.now }, updated: { type: Date, default: Date.now }, comments: { type: [Schema.ObjectId], ref: 'Comment' } }); 

So my comment collection is a collection of object identifier, referencing my comment scheme / comment collection.

I need to remove some of them on request, so I'm trying to do this:

 var comments = [1, 2, 4]; Post.update({ _id: post_id}, {'$pullAll': {comments: comments }}) .exec(function(err) { // How to remove documents with 1, 2, 4 ids from a Comment collection properly }); 

After executing the above code, I deleted the comment identifiers from Post.comments, but I also need to remove these comments from the Comments collection. How can I do it?

EDIT:. How to get the identifiers of documents that were not actually deleted. A simple example:

 Post.comments = [1, 2, 3]; Post.update({ _id: post_id}, {'$pullAll': {comments: [1,2]}}); 

In the above code, Post.com has only 1,2,3, but we are trying to pull out [1,2], so I need to know that id = 3 does not exist on Post.comments, and I don’t need to remove it from the collection ' Comments'.

+4
source share
2 answers

Use $in for this:

 var comments = [1, 2, 4]; Post.update({ _id: post_id}, {'$pullAll': {comments: comments }}) .exec(function(err) { Comment.remove({ _id: { $in: comments }}, function(err, numberRemoved) { // The identified comments are now removed. }); }); }); 
+1
source

You can use the findAndModify command to release the update and return the original document to the value property of the command result. You should not have a problem comparing the returned comments field with the identifier from your $pullAll request to determine which identifier was deleted.

 $ mongo MongoDB shell version: 2.2.0-rc1 connecting to: test > db.posts.drop() true > db.posts.insert({ _id: 1, comments: [1,2,3] }) > db.runCommand({ ... findAndModify: "posts", ... query: { _id: 1 }, ... update: { $pullAll: { comments: [1,2,4] }}, ... }) { "value" : { "_id" : 1, "comments" : [ 1, 2, 3 ] }, "lastErrorObject" : { "updatedExisting" : true, "n" : 1 }, "ok" : 1 } 

As JohnnyHK mentioned in his answer, deleting the comment documents themselves is best done using the remove() query and the $in operator.

Note. The above example uses the Mongo JS shell. It seems that Mongoose recently got a helper method for findAndModify (see PR # 803 ), although you can always execute the database command if it is not available in the version you are using.

+1
source

All Articles