你能帮我看看这段代码吗?这段代码没有从 MongoDB 中删除值,而我正在运行这个 url:http://localhost:3000/delete/57c6713455a6b92e105c5250 .
我收到此响应:{"lastErrorObject":{"n":0},"value":null,"ok":1}
,但没有删除。
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
最佳答案
在 MongoDB 中,您通过使用 ObjectId
构造函数而不是 ObjectId 的字符串来查询文档 id(_id
)。因此查询需要是:{ '_id': ObjectId(uid) }
。
例子
var mongoClient = require('mongodb').MongoClient;
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
mongoClient.connect("Your connection string", function(err, db) {
var query = {
_id: ObjectId("id_string") // Important to notice
};
var collection = db.collection('your collection');
collection.find(query, function(err, docs) {
console.log(err, docs);
});
});
建议
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
//Add object id to query object
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
关于javascript - nodejs mongodb不根据id删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39246853/