【发布时间】:2017-10-14 19:00:30
【问题描述】:
我正在尝试确定是否在我的 findOneAndUpdate 操作中找到了该文档。如果不是,我返回 404 not found 错误。我想我会使用 Mongoose 提供的“passRawValue”选项,并检查原始值 - 如果未定义原始值,我知道找不到文档。
但是,无论是否找到文档,我的原始值都是未定义的。通过在更新前运行一个简单的“findOne”查询,我已经验证了我正在尝试更新的文档在查询时位于数据库中。我哪里错了?
let updateItemById = (userId, itemId, params, cb) => {
//this finds and prints the document I'm testing with -- I know its in the DB
// Item.findOne({ "_id" : itemId, ownerId: userId }, (err, doc) => {
// if (doc) {
// console.log("This is the doc: ", doc);
// }
// });
Item.findOneAndUpdate({ "_id" : itemId, ownerId: userId },
{
$set: {
params
}
}, { runValidators: 1, passRawResult: true}, (err, doc, raw) => {
if (err) {
//winston.log
return cb(ErrorTypes.serverError(), false);
}
else if (raw) {
return cb(null, true);
}
else {
return cb(ErrorTypes.notFound(), false);
}
});
}
【问题讨论】: