我将 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/