我几天来一直试图理解为什么这个删除查询不起作用,但我就是看不出问题所在。
我尝试过许多不同的删除查询,例如deleteOne、findOneAndDelete、deleteMany,但没有一个有效。
我使用 Node.js 的“mongodb”客户端
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).
当我在 MongoClient 这样的软件中使用相同的查询时,它可以工作。
我已经尝试了此网站上发布的许多解决方案,如果错误太明显,我很抱歉,但我完全迷失了。
感谢您的帮助。
最佳答案
问题在于数据库中的 _id
类型为 ObjectId
,但在您的查询中它是 String
类型。您必须对此严格要求,否则查询将与文档不匹配。
试试这个:
const mongodb = require('mongodb');
...
doc.deleteOne({ _id : mongodb.ObjectId(docToDelete) }, (err, results) => {
...
});
关于javascript - Node.js 删除 "mongodb"的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37838896/