问题描述
下面是我的代码
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', {
name: String,
age: {type: Number, default: 20},
create: {type: Date, default: Date.now}
});
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){
if(err){
console.log("Something wrong when updating data!");
}
console.log(doc);
});
我的mongo数据库中已经有一些记录,我想运行此代码来更新年龄为17岁的姓名,然后在代码末尾打印出结果.
I already have some record in my mongo database and I would like to run this code to update name for which age is 17 and then print result out in the end of code.
但是,为什么我仍然从控制台获得相同的结果(而不是修改后的名称),但是当我转到mongo db命令行并键入"db.cats.find();
"时.结果带有修改后的名称.
However, why I still get same result from console(not the modified name) but when I go to mongo db command line and type "db.cats.find();
". The result came with modified name.
然后我再次运行此代码,并修改了结果.
Then I go back to run this code again and the result is modified.
我的问题是:如果修改了数据,那么为什么在console.log上还是第一次获得原始数据.
My question is: If the data was modified, then why I still got original data at first time when console.log it.
推荐答案
为什么会这样?
默认是返回未更改的原始文档.如果要返回更新后的新文档,则必须传递一个附加参数:new
属性设置为true
的对象.
Why this happens?
The default is to return the original, unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: an object with the new
property set to true
.
从猫鼬文档:
Model.findOneAndUpdate(conditions, update, options, (error, doc) => {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
});
可用选项
-
new
:bool-如果为 true ,则返回经过修改的文档,而不是原始文档. 默认为假(已在4.0中更改)
new
: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
解决方案
如果要在doc
变量中更新结果,请通过{new: true}
:
Solution
Pass {new: true}
if you want the updated result in the doc
variable:
// V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
这篇关于猫鼬:findOneAndUpdate不返回更新的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!