下面是我的代码
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它。
解决方法
默认值是返回未更改的文档。如果想要返回新的更新文档,则必须传递一个名为new的附加参数,其值为true。
http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
查询#findOneAndUpdate
function(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变量:
Cat.findOneAndUpdate({age: 17},{new: true},doc){ if(err){ console.log("Something wrong when updating data!"); } console.log(doc); });