MongoDB上的.updateOne不在Node.js中工作 [英] .updateOne on MongoDB not working in Node.js

查看:242
本文介绍了MongoDB上的.updateOne不在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}},无法正常工作

编辑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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆