我正在try 使用NodeJS更新MongoDB的值,这是我的代码:

Controller.js

    updateProduct: async (req, res) => {
        try {
            const { params: { id } } = req;
            const { body } = req;
            if (!body || Object.keys(body).length === 0) {
                Response.ERROR(res, new createError.BadRequest());
            } else {
            let product = await ProductsService.updateP(id, body);
        }
            if (!product) {
                Response.ERROR(res, new createError.NotFound());
            
            } else {
                Response.SUCCSESS(res, 201, `Producto actualizado`, product);
            }
        } catch (error) {
            debug(error);
            Response.ERROR(res);
        }
    },

服务

const updateP = async (id, product) => {
    const collection = await Database(COLLECTION);
    return collection.updateOne({_id: new ObjectId(id)}, { $set: { ...product } })
    
};

DB

 "body": {
        "_id": "651cd5d91e3c20bda7cea881",
        "name": "shoes",
        "price": 359,
        "quantity": 10,
    }

我收到了这样的错误:

MongoServerError: Performing an update on the path '_id' would modify the immutable field '_id'

我调查过了,试着把...product换成req.params.name,但还是不行

我想要这样的东西:

 "body": {
        "_id": "651cd5d91e3c20bda7cea881",
        "name": "Coca-cola",
        "price": 359,
        "quantity": 10,
    }

推荐答案

您遇到的错误是因为MongoDB在文档创建后不允许修改其_id字段.这是一个不变的领域.

在UPDATE函数中,您try 使用扩散操作符(...product)更新文档,该操作符将所有字段(包括_id)从product分布到更新对象中.这就是您看到错误的原因.

要解决此问题,应在try 更新之前从产品对象中删除_id字段:

const updateP = async (id, product) => {
    const collection = await Database(COLLECTION);
    const { _id, ...updateData } = product;  // Remove _id from product
    return collection.updateOne({ _id: new ObjectId(id) }, { $set: updateData });
};

通过以这种方式分解产品对象,您实际上提取了_id字段,其余数据(不包括_id)存储在updateData中.然后,可以在$set运算符中安全地使用该updateData对象,而无需try 修改_id字段.

Node.js相关问答推荐

如何解决TypeError:requ.isAuthenticated不是函数错误?

将文件传递到 AWS lambdas(nodejs) + API 网关后重新上传文件

mongoose.model() 方法返回未定义

如何使用来自前一阶段的另一个数组的聚合mongoose 在数组中添加字段

是Electron 的密码和登录凭据的安全存储吗?

如何更新 MongoDB 中对象数组中的键?

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

等到文件上传完成的有效方法(mongoose )

我可以向NPM添加调试脚本吗?

Node_redis - 如何删除密钥?

将 myproject/.npmrc 与注册表一起使用

判断一个数组中的每个元素是否都在第二个数组中

Dart 语言比 JavaScript (Node.js) 有什么好处

无法获取 CSS 文件

node.js 中存储的模块变量在什么范围内?

- configuration.output.path:提供的值public不是绝对路径!使用 Webpack

我应该如何在 webpack 中使用时刻时区?

将 NodeJS 用于大型项目

为什么 Node.js 没有原生 DOM?

避免在弹性 beantalk 中重建 node_modules