node.js - Mongoose with Bluebird promisifyAll - 模型对象上的 saveAsync 生成一个数组作为已解决的 promise 值

标签 node.js mongoose promise bluebird

我将 bluebird 的 promisifyAll 与 Mongoose 一起使用。当我在模型对象上调用 saveAsync(save 的 promise 版本)时,已完成 promise 的解析值是一个包含两个元素的 数组。第一个是我保存的模型对象,第二个是整数 1。不知道这里发生了什么。下面是重现该问题的示例代码。

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]

我只期望该数组中的第一项,因为 Mongoose 模型 save() 方法返回单个对象。

任何帮助将不胜感激!

最佳答案

警告:此行为从 bluebird 3 开始发生变化 - 在 bluebird 3 中,问题中的默认代码将起作用,除非将特殊参数传递给 promisifyAll。


.save的回调的签名是:

 function (err, product, numberAffected)

由于这不遵守返回一个值的 Node 回调约定,所以bluebird将多值响应转换为数组。该数字表示受影响的项目数(如果在数据库中找到并更新了文档,则为 1)。

你可以通过.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");
})

关于node.js - Mongoose with Bluebird promisifyAll - 模型对象上的 saveAsync 生成一个数组作为已解决的 promise 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25798691/

相关文章:

typescript - 文档类型上不存在属性 "password"

mongodb - Mongoose 重命名集合

mysql - 使用 mySQL 和 Mongodb 进行 Node 循环插入

javascript - Promises 中的异步函数

javascript - 类型错误 : Cannot call method 'then' of undefined Angularjs

javascript - 在其中一个脚本中使用 package.json 的版本属性

angularjs - Node/Express - POST 请求从远程服务器接收 zip,传回客户端

node.js - 当 Amazon EC2 上的 CPU 使用率达到 100% 并且服务器停止时如何重新启动我的 Node js 应用程序

node.js - 带有redis服务器的nod​​e.js中未定义的空错误?

javascript - 对如何使用 .then() 使用 promise 链接查询感到困惑