gpt4 book ai didi

json - Mongoose 错误 : Cast to ObjectID failed for value on reading json for db seed

转载 作者:可可西里 更新时间:2023-11-01 10:02:30 25 4
gpt4 key购买 nike

我有一个带有如下引用字段的模型方案:

const UserSchema = new mongoose.Schema({
// ...
uf:{
type: mongoose.Schema.Types.ObjectId, ref: 'UF', index: true
},
});

我的测试数据库种子代码正在使用来自 json 文件的数据,如下所示:

[
{ "_id": 91283,
"name":"Test user",
"uf": 124411923,
"version": 2
}
]

在种子过程中,模型保存方法后,出现此错误:

ValidationError: User validation failed: uf: Cast to ObjectID failed for value "124411923" at path "uf"
errors:
{ uf:
{ MongooseError: Cast to ObjectID failed for value "124411923" at path "uf"

这是负责加载 json 并保存到数据库的代码,我已经对种子列表进行了排序,以便首先插入 UF:

function seed() {
console.log('Starting db seed...');

return Promise.each(initialData, (data) => {
// path to mongo model js file
let Model = require(data.model);

removeModel(Model)
.then(() => {
console.log('[' + data.name + '] model removed. ');
return saveModel(data, Model);
}).then(() => {
console.log('[' + data.name + '] model saved');
}).catch( (err) => {
console.error('Error seeding db', err);
});
});
}

/**
* Saves model to the database
* @param {*} data
* @param {*} Model
*/
function saveModel(data, Model) {
// path to json data file
let seedList = require(data.seed);

return Promise.map(seedList, function(seed) {
let newItem = new Model(seed);
return newItem.save({});
});
}

有人能帮忙吗?

最佳答案

在您的用户文档中,您没有包含有效的 ObjectId,因此当您尝试存储为 ObjectId 类型时出现错误。

Refs 只能保护 _id 字段不受其他集合的影响。

因此,在您的用户文档中,您需要包含对 UF 集合中的 _id 字段的引用:

[
{
"_id": 91283,
"name":"Test user",
"uf": [_id from UF here],
"version": 2
}
]

注意:如果您在 UF 模式中明确定义了 _id 字段为 Number 类型,那么您可以通过匹配类型从您的用户模式中引用它:

const UserSchema = new mongoose.Schema({
// ...
uf: {
type: Number, ref: 'UF', index: true
},
});

关于json - Mongoose 错误 : Cast to ObjectID failed for value on reading json for db seed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com