需要帮助。有一个我用api构建的mongoose文件;我需要从另一个mongoose查询引用填充country字段。一切正常,期待我可以在我用来检索第二个对象的函数中访问我的第一个文档对象
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');
答案 0 :(得分:1)
Bergi正走在正确的轨道上,Mongoose可以归还承诺。但是,findByIdQelasy
不会返回承诺。您需要致电exec()
以获得承诺。
Q(country.findByIdQelasy(object.country.id).exec()).then(function (res) {
instituteQelasy.country = res._id;
});