猫鼬与蓝鸟promisifyAll-模型对象上的saveAsync导致将数组作为已解析的承诺值 [英] Mongoose with Bluebird promisifyAll - saveAsync on model object results in an Array as the resolved promise value

查看:105
本文介绍了猫鼬与蓝鸟promisifyAll-模型对象上的saveAsync导致将数组作为已解析的承诺值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将蓝鸟的promisifyAll与猫鼬一起使用.当我在模型对象上调用saveAsync(保存的承诺版本)时,已完成Promise的解析值是带有两个元素的数组.第一个是我保存的模型对象,第二个是整数1 .不知道这是怎么回事.下面是重现此问题的示例代码.

I'm using bluebird's promisifyAll with mongoose. When I call saveAsync (the promisified version of save) on a model object, the resolved value of the completed promise is an array with two elements. The first is my saved model object, the second is the integer 1. Not sure what's going on here. Below is example code to reproduce the issue.

var mongoose = require("mongoose");

var Promise = require("bluebird");


Promise.promisifyAll(mongoose);


var PersonSchema = mongoose.Schema({
    'name': String
});

var Person = mongoose.model('Person', PersonSchema);

mongoose.connect('mongodb://localhost/testmongoose');


var person = new Person({ name: "Joe Smith "});

person.saveAsync()
.then(function(savedPerson) {
    //savedPerson will be an array.  
    //The first element is the saved instance of person
    //The second element is the number 1
    console.log(JSON.stringify(savedPerson));
})
.catch(function(err) {
    console.log("There was an error");
})

我得到的答复是

[{"__v":0,"name":"Joe Smith ","_id":"5412338e201a0e1af750cf6f"},1]

由于猫鼬模型save()方法返回单个对象,所以我只希望该数组中的第一项.

I was expecting just the first item in that array, as the mongoose model save() method returns a single object.

任何帮助将不胜感激!

推荐答案

警告::此行为从bluebird 3开始更改-在bluebird 3中,问题中的默认代码将起作用,除非使用特殊参数被传递给promisifyAll.

Warning: This behavior changes as of bluebird 3 - in bluebird 3 the default code in the question will work unless a special argument will be passed to promisifyAll.

.save的回调的签名是:

 function (err, product, numberAffected)

由于这不遵守返回一个值的节点回调约定,因此bluebird将多值响应转换为数组.该数字表示生效的项目数(如果在数据库中找到并更新了文档,则为1).

Since this does not abide to the node callback convention of returning one value, bluebird converts the multiple valued response into an array. The number represents the number of items effected (1 if the document was found and updated in the DB).

您可以通过.spread获得语法糖:

You can get syntactic sugar with .spread:

person.saveAsync()
.spread(function(savedPerson, numAffected) {
    //savedPerson will be the person
    //you may omit the second argument if you don't care about it
    console.log(JSON.stringify(savedPerson));
})
.catch(function(err) {
    console.log("There was an error");
})

这篇关于猫鼬与蓝鸟promisifyAll-模型对象上的saveAsync导致将数组作为已解析的承诺值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆