2

I have been trying to understand why this delete query doesn't work for days, and I just can't see the problem.
I've tried many different delete queries like deleteOne, findOneAndDelete, deleteMany but none of them worked.
I use the "mongodb" client for node.js

mongo.connect(serverAddress, (err, db) => {
//(db connection is ok, server can find and create documents)

    var doc = db.collection('myCollection'),
    docToDelete = "575807172154b7a019ebf6db"; 
    //I can see the same document id on my database

    doc.deleteOne({"_id":docToDelete}, (err, results) => { 
        console.log(`Request success : ${results.result.ok}, documents deleted : ${results.result.n}`);
        //Request success : 1, documents deleted : 0, the document is still on my database
    });
}
//the doc var is the same I use to add/find documents (and it works).

When I use the same query in softwares like MongoClient, it works.
I have tried many solutions posted on this site and sorry if the error is too obvious but I'm totaly lost.
Thanks for your help.

1 Answer 1

4

The problem is that _id in the database is of type ObjectId, but in your query it's a String. You have to be strict about that, otherwise the query won't match the document.

Try this:

const mongodb = require('mongodb');
...
doc.deleteOne({ _id : mongodb.ObjectId(docToDelete) }, (err, results) => {
  ...
});
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks ! I remember having seen this ObjectId method somewhere in mongo documentation but I did not make the connection ...

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.