gpt4 book ai didi

node.js - 带有自己的 ObjectId 的 Mongoose 自引用抛出 : cast to ObjectId failed

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

我正在使用 nodejs、 Mongoose ,我试图构建一个 shema,其中包含通过父级对自身的引用。 Parent 应该是对 DataType 的引用。

var DataTypeSchema = new Schema({
_id: String,
label: { type: String, required: true },
comment: { type: String },
url: { type: String, required: true },
parent: { type: Schema.Types.ObjectId, ref: 'DataType' },
values: []
});

var DataType = mongoose.model('DataType', DataTypeSchema);
module.exports.DataType = DataType;

每个 DataType 都有自己的 ID(不是由 mongo 生成的),我认为这是导致问题的地方。它向我抛出错误 cast to objectid failed for value "Number"at path "parent",其中 Number 是 ID 为“Number”的对象已保存在数据库中。

谢谢

最佳答案

parent 引用的类型必须与其引用的模型中的 _id 的类型相匹配。所以 Schema.Types.ObjectId 应该是 String:

...
parent: { type: String, ref: 'DataType' },

关于node.js - 带有自己的 ObjectId 的 Mongoose 自引用抛出 : cast to ObjectId failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26018412/

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