MongoDB 上的 .updateOne 在 Node.js 中不起作用 [英] .updateOne on MongoDB not working in Node.js
问题描述
我有以下代码:
connection((db) => {
db.collection('orders')
.updateOne(
{ "_id": req.body._id}, // Filter
{"name": req.body.name} // Update
)
.then((obj) => {
console.log('Updated - ' + obj);
res.redirect('orders')
})
.catch((err) => {
console.log('Error: ' + err);
})
})
我想更改订单中的名称但它没有更新它.控制台中的结果是
I want to change the name in the order but it doesn't update it. The result in the console is
更新 - {"n":0,"nModified":0,"ok":1}
我试图阅读文档,但它太可怕了
I tried to read the documentation but it's horrific
{$set: {"name": req.body.name}},
效果不佳
EDIT 2:传递的 ID 与数据库中的 _id 匹配.我在数据库中查询纯文本 ID 是否有问题,它被称为ObjectId('5a42ja...')"
EDIT 2: The passed ID matches the _id in the database. Could it be a problem that I'm querying for plain text ID while in the database it is referred to as "ObjectId('5a42ja...')"
推荐答案
也许你应该像这样在更新查询中使用$set":
Maybe you should use "$set" in your update query like this :
{$set: {"name": req.body.name}}, // Update
编辑
如果它不起作用,这可能是因为与您的过滤器不匹配.
If it doesn't work, this is probably because there is no match with your filter.
也许你应该尝试像这样匹配一个 ObjectId :
Maybe you should try to match with an ObjectId like this :
var ObjectID = require('mongodb').ObjectID;
// In your request
{ "_id": ObjectID(req.body._id)}, // Filter
希望有帮助.
这篇关于MongoDB 上的 .updateOne 在 Node.js 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!