Javascript MongoDB 上的 .updateOne 在 Node.js 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47656515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:54:03  来源:igfitidea点击:

.updateOne on MongoDB not working in Node.js

javascriptnode.jsmongodbmongodb-query

提问by Simeon Nakov

I have the following code:

我有以下代码:

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

我想更改订单中的名称,但它没有更新它。控制台中的结果是

Updated - {"n":0,"nModified":0,"ok":1}

Updated - {"n":0,"nModified":0,"ok":1}

I tried to read the documentation but it's horrific

我试图阅读文档,但这太可怕了

EDIT: {$set: {"name": req.body.name}},didn't work as well

编辑:{$set: {"name": req.body.name}},效果不佳

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...')"

编辑 2:传递的 ID 与数据库中的 _id 匹配。我在数据库中查询纯文本 ID 是否有问题,它被称为“ObjectId('5a42ja...')”

回答by Sparw

Maybe you should use "$set" in your update query like this :

也许您应该在更新查询中使用“$set”,如下所示:

{$set: {"name": req.body.name}}, // Update

More information in documentation

文档中的更多信息

EDIT

编辑

If it doesn't work, this is probably because there is no match with your filter.

如果它不起作用,这可能是因为与您的过滤器不匹配。

Maybe you should try to match with an ObjectId like this :

也许您应该尝试与这样的 ObjectId 匹配:

var ObjectID = require('mongodb').ObjectID;

// In your request
{ "_id": ObjectID(req.body._id)}, // Filter

Hope it helps.

希望能帮助到你。

回答by Dan Porat

Use {$set: {"name": req.body.name}}(as Sparw mentioned) to update the the properties you want in the document. Also, if the id that you pass as a parameter does not exists in the collection (and you want to create one with the same id) you can pass as a third parameter {upsert: true}to create one.

使用{$set: {"name": req.body.name}}(如 Sparw 提到的)更新文档中所需的属性。此外,如果您作为参数传递的 id 在集合中不存在(并且您想创建一个具有相同 id 的 id),您可以作为第三个参数传递{upsert: true}来创建一个。

In your example:

在你的例子中:

connection((db) => {
          db.collection('orders')
               .updateOne(
                  { "_id": req.body._id}, // Filter
                  {$set: {"name": req.body.name}}, // Update
                  {upsert: true} // add document with req.body._id if not exists 

             )
            .then((obj) => {
               console.log('Updated - ' + obj);
              res.redirect('orders')
         })
        .catch((err) => {
           console.log('Error: ' + err);
      }) })

回答by MajidJafari

Tough @Spraw's answer is right for some cases, but sometimes it doesn't work. I think the convenient answer is updateOne({_id: new ObjectID(req.body._id)}, {$set: {"name": req.body.name}}, callback).

强硬的@Spraw 的答案在某些情况下是正确的,但有时它不起作用。我认为方便的答案是updateOne({_id: new ObjectID(req.body._id)}, {$set: {"name": req.body.name}}, callback)

the _idin mongodbis a BSONobject and should be instantiated.

_idmongodb是一个BSON对象,并应被实例化。

回答by Victor Vargas

The correct syntax is:

正确的语法是:

monDb.collection.updateOne(
    {"_id": ObjectID(req.params.id)}, 
    { $set: updateDoc }, 
    function(err, doc) {
      ...
    }
);

回答by maiko

For me, I have to delete the "_id"/id field before passing the object in the update.

对我来说,在更新中传递对象之前,我必须删除“_id”/id 字段。

Or it will say that the field is invalid.

或者它会说该字段无效。

Obviously, updated the key while you're using it as a reference isn't the best thing to do.

显然,在您将其用作参考时更新密钥并不是最好的做法。

回答by EMMANUEL OKELLO

Too late but for newbies or students learning nodejs with mongodb. instead of updateOnemethod, just use the updatemethod.

太晚了,但是对于使用 mongodb 学习 nodejs 的新手或学生来说。而不是updateOne方法,只需使用update方法。

connection((db) => {
          db.collection('orders')
               .update(
                  { "_id": req.body._id}, // Filter
                  {$set: {"name": req.body.name}}, // Update
                  {upsert: true} // add document with req.body._id if not exists 

             )
            .then((obj) => {
               console.log('Updated - ' + obj);
              res.redirect('orders')
         })
        .catch((err) => {
           console.log('Error: ' + err);
      }) })