猫鼬设置referenceone

时间:2015-05-26 17:07:58

标签: javascript node.js mongodb asynchronous mongoose

你好,有人可以帮助我。我无法设置mongoose模型字段

这是我的institute.js模型文件

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var instituteSchema = new Schema({
    name: {type: String, required: true},
    idApi: {type: String, required: true},
    country: {
        type: Schema.ObjectId,
        ref: 'Country'
    },
    created_at: {type: Date, default: Date.now}
}, {collection: 'qel_par_institute', versionKey: false});

instituteSchema.methods.findByIdApi = function (id, callback) {
    return mongoose.model('Institute').findOne().where('idApi').equals(id).exec(callback);
}

instituteSchema.methods.findByCountry = function (id, callback) {
    return mongoose.model('Institute').find().where('country.id').equals(id).exec(callback);
}

mongoose.model('Institute', instituteSchema);

有sync.js部分保持工作除了我不能手动设置国家参考不是另一个字段

var instituteApi = new instituteModel({
    name: item.name,
    idFromApi: item.id
});
if (typeof item.country.id !== 'undefined') {
    var country = new countryModel();
    country.findByIdApi(item.country.id, function(err, res) {
        if (err) 
            console.log(err);

        if (res) {
            instituteApi.country = res._id; //setting this way doesn't work
        }
    })
}
instituteApi.save(function(err) {
    if (err)
        console.log('something went wrong while saving!');
});

1 个答案:

答案 0 :(得分:0)

无法设置它,因为异步调用。切换回调以承诺Q module。一切都按照需要运作