【问题标题】:Promises in nodejs with Q save ref to mongoose带有 Q 的 nodejs 中的 Promise 将 ref 保存到 mongoose
【发布时间】:2015-08-11 05:54:06
【问题描述】:

需要帮助。有一个我从 api 构建的猫鼬文档;我需要参考另一个猫鼬查询来填充国家/地区字段。一切正常,希望我可以在用于检索第二个对象的函数中访问我的第一个文档对象

var instituteQelasy;
if (res) {
    instituteQelasy = res;
    instituteQelasy.name = object.name;
} else {
    instituteQelasy = new instituteModel({
        name: object.name,
        idQelasy: object.id
    });
}

if (typeof object.country.id !== 'undefined') {
    var country = new countryModel();
    var countryRef = country.findByIdQelasy(object.country.id, function(err, res) {
        var deferred = Q.defer();
        if (err) {
            deferred.reject(err);
        }

        if (res) {
            deferred.resolve(res._id);
        }

        return deferred.promise;
    });

    countryRef(res).then(function(data) {
        instituteQelasy.country = data;
    });
}

instituteQelasy.save(function(err) {
    if (err)
        console.log('something went wrong while saving!');
});

编辑:既然你们指的是实习生猫鼬。这是我的文件的样子 我的 country.js 看起来像以及为什么我没有使用 mongoose 承诺

var mongoose = require('mongoose');
var env = process.env.NODE_ENV || 'development';
var config = require('../config/config')[env];
var Schema = mongoose.Schema;

var countrySchema = new Schema({
    name: {type: String, required: true},
    idQelasy: {type: String, required: true},
    created_at: {type: Date, default: Date.now}
}, {collection: 'qel_par_country', versionKey: false});

countrySchema.methods.findByIdQelasy = function (id, callback) {
    return mongoose.model('Country').findOne().where('idQelasy').equals(id).exec(callback);
}

countrySchema.methods.findByName = function (name, callback) {
    return mongoose.model('Country').findOne().where('name').equals(name).exec(callback);
}

mongoose.model('Country', countrySchema);

然后我像这样将它导入到我的 server.js 文件中

var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function (file) {
    require(models_path + '/' + file);
});
var countryModel = mongoose.model('Country');

【问题讨论】:

  • 猫鼬不是已经返回承诺了吗?就做var countryRef = Q(country.findByIdQelasy(object.country.id))
  • 感谢您的反馈,但得到了:{ state: 'pending' }

标签: javascript node.js mongoose promise


【解决方案1】:

Bergi 正走在 Mongoose 可以兑现承诺的正确轨道上。但是,findByIdQelasy 不会返回承诺。您需要致电exec() 以获得承诺。

Q(country.findByIdQelasy(object.country.id).exec()).then(function (res) {
    instituteQelasy.country = res._id;
});

【讨论】:

  • 感谢您对猫鼬承诺的正确回答。查看我的编辑
猜你喜欢
  • 2016-05-08
  • 2017-01-09
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多