我收到了对ObjectId的强制转换错误,我真的看不出原因:
CastError:对于值" [对象对象]"转换为ObjectId失败在路径"州"
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'
}]
更奇怪的是,数据在数据库中正确填充。任何人都可以看到为什么我收到错误?
答案 0 :(得分:1)
实际上这不是错误:
stateModel.country = countryModel._id;
这是错误:
countryModel.states.push(state)
当国家/地区的架构具有ObjectId ref for state时,我正在推送整个状态对象。
这是正确答案:
countryModel.states.push(state._id)