How to remove a document in Mongoose, only if one of its fields matches some condition?

2.8k Views Asked by At

I want to delete one item only if it matches some condition. It would be something like this:

Session.findOne({ id:req.body.sessionId },function(err,session){
    if(session.user == req.body.userId) {
        session.remove();
    }
});

Which obviously doesn't work. How can I achieve that?

3

There are 3 best solutions below

0
On BEST ANSWER

You can test multiple conditions at the same time in Mongoose. This should work for you.

Session.findOne({ 
  id: req.body.sessionId,
  user: req.body.userId
})
.remove()
.exec();
2
On

Can you not just combine the query?

Session.findOne({ id:req.body.sessionId, user: req.body.userId}).remove( callback );
6
On

Honestly, just do :

Session.remove({ "_id": req.body.sessionId },function(err,result) {

});

That's more efficient and safe.

The reason it's failing in your example is because the variable is not a string anymore but an ObjectId in the returned document. But it's not really safe so don't do it that way.


If you are being paranoid about the matching session then do it first:

if (session.user.toString() == req.body.userId) {
    Session.remove({ "_id": req.body.sessionId },function(err,result) {

    });
} else {
   // Not the same
}

And be aware that an ObjectId is not the same as a string in the request. Convert or cast one of them.