Mantissa
Mantissa

Reputation: 91

Cannot remove on mongodb using mongoose?

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.

Upvotes: 0

Views: 3118

Answers (2)

tcetin
tcetin

Reputation: 1089

Just add exec() after query.

It should work like this:

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

Upvotes: 0

sfritter
sfritter

Reputation: 891

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.

Upvotes: 1

Related Questions