nodejs中带有Q的承诺保存引用到mongoose

Promises in nodejs with Q save ref to mongoose

本文关键字:保存 引用 mongoose 承诺 nodejs      更新时间:2023-09-26

需要帮助。有一个猫鼬文件,我从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 promises

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');

Bergi在正确的轨道上,Mongoose可以返回承诺。但是,findByIdQelasy不返回承诺。你需要打电话给exec()来得到一个承诺。

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