使用mongoose和Q.spread给出了数组回调参数

时间:2014-04-24 11:31:14

标签: node.js mongoose q

我有以下代码:

var mongoose = require('mongoose');
var Q = require("q")
mongoose.connect("mongodb://localhost/testdb");

var Schema = mongoose.Schema;
var employeeSchema = new Schema({
    name:String
})
var Employee = mongoose.model('Employee', employeeSchema);

var departmentSchema = new Schema({
    name:String
})

var Department = mongoose.model('Department', departmentSchema);

var employee = new Employee();
employee.name = "T.Smith";
var dept = new Department();
dept.name = "Sales";


Q.spread([
    Q.nfcall(employee.save.bind(employee)),
    Q.nfcall(dept.save.bind(dept))
],function(emp,dept){
    console.log(JSON.stringify(emp));
    console.log(JSON.stringify(dept));
    mongoose.disconnect();
})

日志语句将产生以下结果:

  

[{ “__ V”:0, “名称”: “T.Smith”, “_ ID”: “5358f3c53cd354bc70fe619f”},1]   [{ “__v”:0, “姓名”: “销售”, “_ ID”: “5358f3c53cd354bc70fe61a0”},1]

为什么结果是数组而不是单个对象?

如果我用这个块替换最后一段代码,我会得到同样的结果:

Q.all([
    Q.nfcall(employee.save.bind(employee)),
    Q.nfcall(dept.save.bind(dept))
]).spread(function(emp,dept){
    console.log(JSON.stringify(emp));
    console.log(JSON.stringify(dept));
    mongoose.disconnect();
})

顺便提一下,建议使用哪个块?

1 个答案:

答案 0 :(得分:1)

保存回调签名是function(err, result, numberAffected),它不符合节点回调约定。 nfcall需要一个节点回调签名,即function(err, result)。为避免信息丢失,nfcall返回的承诺解析为[result, numberAffected]

无论如何,在呼叫站点使用.bindQ.nfcall非常难看,因此您可以创建一个完成所有这些操作的方法:

mongoose.Model.prototype.saveForResult = function() {
    return Q.nbind(this.save, this)().spread(function(result, numberAffected) {
        return result;
    });
};

然后:

Q.spread([
    employee.saveForResult(),
    dept.saveForResult()
],function(emp,dept){
    console.log(JSON.stringify(emp));
    console.log(JSON.stringify(dept));
    mongoose.disconnect();
})