mongoose使用bluebird作为promise,update后无法通过exec获取更新后的数据
发布于 8 年前 作者 fsy0718 5953 次浏览 来自 问答

用bluebird将mongoose中所有的方法进行promise化,当一个model进行update后返回的query变成promise,无法通过exec获取到更新的数据

	var Promise = require('bluebird');
	var PersonSchema = mongoose.Schema({
		name: 'fsy'
	 });
	 var Person = mongoose.model('person', PersonSchema);
	 Promise.promisifyAll(Person);
	 Promise.promisifyAll(Person.prototype);
	 //假若db中有一个_id为123的document
	 Person.update({_id: 123},{name: 'aho'}).exec().then(function(result){
          //这里取到的result是更新数据统计
	 })
	//无法通过官网说的exec取到数据  [Model#update](http://mongoosejs.com/docs/api.html#model_Model.update)
6 回复

mongoose自带promise技能啊

楼上几位真是够了

应该是 .execAsync()

 Person.update({_id: 123},{name: 'aho'}).execAsync().then(function(result){
		//这里取到的result是更新数据统计
 })

如果用bluebirld 替换mongoose原来的promise 应该

var Promise = require('bluebird');
mongoose.Promise = Promise;

官方文档 http://mongoosejs.com/docs/promises.html

@jinwyp 在update后execAsync返回的是更新前的数据,后面我改成mongoose官网推荐的promise写法看看

@fsy0718 在update后execAsync返回的是更新前的数据是另外一个问题, 需要看mongo的findAndModify 文档 有个参数 new : true

https://docs.mongodb.org/v3.0/reference/method/db.collection.findAndModify/

update 本身不返回 更新后的文档 需要用 findAndModify

http://stackoverflow.com/questions/20667739/return-updated-collection-with-mongoose

@jinwyp 十分感谢,文档没看清楚 1.update方法已经说明不会返回更新后的数据

Updates documents in the database without returning them.

2.update当传入callback后,就不能再用exec,我以为callback中是更新数据的统计,exec中返回更新后的数据

To update documents without waiting for a response from MongoDB, do not pass a callback, then call exec on the returned Query:

  1. mongoose中的findOneAndUpdate、findByIdAndUpdate对应mongod中的findAndModify,可以传入new参数
回到顶部