我正在为我的婚礼建造一个桌子计划器,其中包括将客人分配到桌子上。我有一张桌子'模型如下:
const tableSchema = new mongoose.Schema({
name: {
type: String,
required: 'Please provide the name of the table',
trim: true
},
capacity: {
type: Number,
required: 'Please provide the capacity of the table',
},
guests: {
type: mongoose.Schema.ObjectId,
ref: 'Guest',
}
});

我希望Table模型的每条记录都有一个名为guests的属性,它将返回一个guest虚拟机ID数组。我已经设置了以下要导入的JSON文件:
[
{
"firstname": "Name1",
"surname": "Surname1",
"table": "5ad9fe819c2a33f9edcd33b5"
},
{
"firstname": "Name2",
"surname": "Surname2",
"table": "5ad9fe819c2a33f9edcd33b5"
},
{
"firstname": "Name3",
"surname": "Surname3",
"table": "5ad9fe819c2a33f9edcd33b5"
},
{
"firstname": "Name4",
"surname": "Surname4",
"table": "5ad9fe819c2a33f9edcd33b5"
}
]

但是当我尝试导入它时,我收到以下错误:
对于值#34投降到ObjectID失败; [' 5ae2e655c122b654ba3765b4',
' 5ae2e655c122b654ba3765b5',' 5ae2e655c122b654ba3765b6',
' 5ae2e655c122b654ba3765b7',' 5ae2e655c122b654ba3765b8' ]"在路上 "客人"
这个数组对我来说很合适,当我用它将数据导入另一个不包含数组的模型时,我使用的导入脚本运行正常。
有什么想法吗?
答案 0 :(得分:1)
我认为你错误地将guests
定义为ObjectId
,而应该是ObjectIds
的数组。并且,这就是为什么它无法将ObjectIds
的数组转换为ObjectId
,因此出现上述错误。
您的架构看起来应该是这样的:
const tableSchema = new mongoose.Schema({
name: {
type: String,
required: 'Please provide the name of the table',
trim: true
},
capacity: {
type: Number,
required: 'Please provide the capacity of the table',
},
guests: [{
type: mongoose.Schema.ObjectId,
ref: 'Guest',
}]
})