下面是我的代码
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岁的名字,然后在代码的末尾打印结果。
但是,为什么当我转到mongo db命令行并键入“db.cats.find();
”时,我仍然从控制台(不是修改后的名称)得到相同的结果。结果带有修改过的名称。
然后我回去再次运行这段代码,结果被修改了。
我的问题是:如果数据被修改了,那么为什么我第一次在console.log it时仍然得到原始数据。
默认值是返回原始的,未更改的文档。如果希望返回更新后的新文档,则必须传递一个附加参数:一个new
属性设置为true
的对象。
猫鼬文献:
查询#FindOneAndUpdate
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,则返回修改后的文档而不是原始文档。默认值为false(在4.0中更改)如果希望doc
变量中的更新结果,请传递{new:true}
:
// 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);
});
对于使用Node.js驱动程序而不是Mongoose的任何人,您将希望使用{returnoriginal:false}
而不是{new:true}
。
因此,“findoneAndUpdate”需要一个选项来返回原始文档。并且,选项是:
{ReturnNewDocument:true}
参考:https://docs.mongodb.com/manual/reference/method/db.collection.findoneandupdate/
{new:true}
参考:http://mongoosejs.com/docs/api.html#query_query-findoneandupdate
{returnoriginal:false}
参考:http://mongodb.github.io/node-mongodb-native/3.0/api/collection.html#findoneandupdate