【问题标题】:Mongoose - ObjectId failed for value "[object Object]" at path "states"Mongoose - 路径“状态”处的值“[对象对象]”的 ObjectId 失败
【发布时间】:2015-02-03 04:22:52
【问题描述】:

我收到 ObjectId 的转换错误,我真的不明白为什么:

CastError: Cast to ObjectId failed for value "[object Object]" at path "states"

  var data = require('../../../data/seed/refs/countries/countries.json');
    model.Super_CountryRefs.find({}).exec(function (err, collection) {
        if (collection.length === 0) {
            data.forEach(function (country) {
                var countryModel = new model.Super_CountryRefs;
                var country_id = mongoose.Types.ObjectId();
                countryModel._id = country_id;
                countryModel.name = country.name;
                countryModel.abbr = country.abbr;
                countryModel.code = country.code;
                countryModel.flag = country.flag;
                if(country.states != undefined){
                    if(country.states.length > 0){
                        country.states.forEach(function(state){
                            console.log('State: ' + state.name)
                            var stateModel = new model.Super_StateProvinceRefs;
                            stateModel.name = state.name;
                            stateModel.abbr = state.abbr;
EXCEPTION BEING THROWN HERE --> stateModel.country = countryModel._id;
                            stateModel.save(function(err){
                                if(err){
                                    console.log('Error: ' + err)
                                } else {
                                    countryModel.states.push(state)
                                }
                            })
                        })
                    }
                }

                countryModel.save(function(err){
                    if(err)
                        console.log('Error: ' + err);
                })
            })
            console.log('Country/State Seed Complete');
        }
    });

我的国家模型:

        country: {
        type: Schema.ObjectId,
        ref: 'SuperCountry',
        required: 'Country is required'
    }

我的国家模型:

    states : [{
        type: Schema.ObjectId,
        ref: 'SuperStateProvinceRefs'
}]

为了让事情变得更奇怪,数据被正确地填充到了数据库中。谁能看到我为什么会收到错误?

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    其实这不是错误:

        stateModel.country = countryModel._id;
    

    这是错误:

       countryModel.states.push(state)
    

    当国家/地区的架构具有状态的 ObjectId 引用时,我正在推送整个状态对象。

    这是正确答案:

        countryModel.states.push(state._id)
    

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2020-04-18
      • 2017-05-26
      • 2020-11-10
      • 2015-07-16
      • 1970-01-01
      • 2021-05-12
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多