【问题标题】:mongoose setting referenceone猫鼬设置参考
【发布时间】:2015-08-08 11:55:59
【问题描述】:

你好,谁能帮帮我。我无法设置猫鼬模型字段

这里是我的institution.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!');
});

【问题讨论】:

  • 哎呀:全局变量instructionApi未在sync.js中定义

标签: javascript node.js mongodb asynchronous mongoose


【解决方案1】:

由于异步调用,无法设置。使用Q module 将回调切换为承诺。一切都按要求进行

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 2015-03-16
    • 2016-07-02
    • 1970-01-01
    • 2016-11-02
    • 2017-09-13
    • 2015-01-13
    • 2015-01-14
    相关资源
    最近更新 更多