0

Hi im trying to simply remove a document from a collection using mongoose but for some strange reason I cannot get it to work.

Here is the code:

 function deleteUserevent()
{console.log('in delete User Event');

    models.Userevent.remove({ _id: "5214f4050acb53fe31000004"}, function(err) {
    if (!err){
           console.log('deleted user event!');
    }
    else {
           console.log('error');
    }

});
}

Can anyone help me out on my syntax? I know the _id is stored as new ObjectId("5214f4050acb53fe31000004") but I have tried this with no joy?

Thanks.

1
  • 1
    What happens instead? Does it print "error" or does it printed "deleted user event" without deleting, or does it print nothing at all, or does it print a call trace? Commented Aug 22, 2013 at 3:02

2 Answers 2

1

In MongoDB, the "_id" field of documents is of type ObjectId, as you mentioned. This is not equal to a String, so running the query

db.userevent.remove({ _id: "5214f4050acb53fe31000004"});

will not match anything, and will not remove anything. Instead, you must search for a document where the _id field is an ObjectId with that value:

db.userevents.remove({ _id: ObjectId("5214f4050acb53fe31000004")});

In mongoose, you can use the findByIdAndRemove command to remove a document with a specific _id. This command takes either an ObjectId or a String as an argument, so

query = Userevent.findByIdAndRemove("5214f4050acb53fe31000004");

should work just fine.

Sign up to request clarification or add additional context in comments.

Comments

0

Just add exec() after query.

It should work like this:

await models.Userevent.findByIdAndDelete("5214f4050acb53fe31000004").exec()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.