CNode

mongoose使用bluebird作为promise,update后无法通过exec获取更新后的数据

问答
Ffsy0718发布于10 年前最后回复10 年前6 回复6816 浏览0 收藏

用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)

K
klausgao#1·10 年前

mongoose自带promise技能啊

S
simongfxu#2·10 年前
J
jinwyp#3·10 年前

楼上几位真是够了

应该是 .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

F
fsy0718#4·10 年前
引用 jinwyp楼上几位真是够了 应该是 .execAsync() Person.update({ id: 123},{name: 'aho'}).execAsync().then(function(resu...

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

J
jinwyp#5·10 年前
引用 fsy0718@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

F
fsy0718#6·10 年前
引用 jinwyp@fsy0718 在update后execAsync返回的是更新前的数据是另外一个问题, 需要看mongo的findAndModify 文档 有个参数 new : true https://d...

@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参数
参与回复
登录后即可参与回复。登录