我在更新 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/