javascript - multi或upsert设置为true后,MongoDB不更新记录并且promise保持失败

标签 javascript node.js mongodb

我在更新 MongoDB 中的记录时遇到问题(使用 mongoose)。我的代码可以工作,但不更新记录。请参阅下面的代码:

edit(req, res, next) {
var WorkType = require('../models/WorkType');
WorkType.update({id: req.params.id}, {name: req.body.name}, false, false)
    .then(workType => {
        res.send(200, {message: 'Work Type updated successfully'});
    })
    .catch(err => {
        return next(err);
    })
}

此代码运行,但不更新数据库中的信息。 POSTMAN 请求返回 HTTP Status 200 OK 并显示消息:

{ "message": "Work Type updated successfully" }

当我将代码更改为此时

WorkType.update({id: req.params.id}, {name: req.body.name}, false, true)

我遇到了这个错误:

TypeError: Cannot read property 'then' of undefined

throw er; // Unhandled 'error' event

类型错误:callback.apply 不是函数

如果我将代码更改为以下代码:

WorkType.update({id: req.params.id}, {name: req.body.name}, true, false)

我遇到错误:

TypeError: Cannot use 'in' operator to search for 'strict' in true

你能帮我找出问题出在哪里或者为什么 Promise 不适用于第二个代码吗?非常感谢您的帮助!

<小时/>

工作类型.js

var mongoose = require('mongoose');

var WorkTypeSchema = new mongoose.Schema({
name: {
    type: String,
    unique: true,
    required: true
}
})

var WorkType = mongoose.model('WorkType', WorkTypeSchema);

module.exports = WorkType;

最佳答案

update方法的签名是:

Model.update(conditions, update, options, callback)

如果你想使用 Promise,那么你不应该传递回调,这样 Mongoose 就会知道返回一个 Promise。但是,您在此处为回调参数传递值 true:

WorkType.update({ id: req.params.id }, { name: req.body.name }, false, true)

options 参数应为 object 类型,但您在此处传递值 true:

WorkType.update({ id: req.params.id }, { name: req.body.name }, true, false)

您可以传递一个对象作为选项参数,例如:

{ multi: true, upsert: true }

选项回调参数传递false,就像在原始代码中一样,应该可以工作,因为如果不是< em>真相。

关于javascript - multi或upsert设置为true后,MongoDB不更新记录并且promise保持失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47228519/

相关文章:

javascript - 分离的 node.js 应用程序中的 Redis 客户端

javascript - 通过分配新变量来缩短属性路径是个好主意吗?

node.js - Npm 安装失败,docker buildx linux/arm64

MongoDB 填充说明

spring - 在 Spring 测试中忽略 MongoDB 套接字连接

javascript - 数组中的每个字符都被 javascript 中的 ".hasOwnProperty(i)"识别为 Google Apps 脚本的 true

javascript - Textarea 在 IOS 上只允许输入一个字符。如何解决?

ruby-on-rails - 使用 Mongoid 的货币数据类型

javascript - Node JS、Cheerio、获取 XML 版本

javascript - 将参数传递给 React 中的方法