【发布时间】:2020-12-26 23:53:23
【问题描述】:
我正在使用猫鼬,我有以下型号:
const UniversitySchema = new Schema({
name: {
type: String,
required: [true, 'Name is required']
},
color: {
type: String
},
paths: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Path'
}]
})
我希望能够在第一次创建它时将多个路径(转换为路径模型)插入到大学集合中。我尝试了以下代码:
const newUni = new University({
name: name,
paths: [...pathIds],
color: color
})
newUni.save()
.then(uni => {
return res.send(uni)
})
.catch(err => console.log(err));
})
但它会引发此错误:
CastError: Cast to ObjectId failed for value "[ 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ]" at path "_id" for model "Path"
messageFormat: undefined,
stringValue: '"[ 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ]"',
kind: 'ObjectId',
value: [ 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ],
path: '_id',
reason: Error: Argument passed in must be a single String of 12 bytes or a string
of 24 hex characters
看起来mongoose在有多个ID时不会单独投射ID,因为当我尝试使用一个ID时,它起作用了。
我也尝试过保存文档,然后将 ids 推送到路径数组,但没有成功。
有没有办法一次性完成?
提前致谢。
【问题讨论】:
标签: javascript node.js express mongoose nosql