mongoose用自己的ObjectId引用自我引用抛出:强制转换为ObjectId失败

我正在使用nodejs,mongoose,我试图build立一个shema包含通过父母的引用。 父应该是对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生成),我认为这是一个导致问题的地方。 它抛出一个错误转换objectid失败的价值“数字”的path“父母” ,其中数字是ID为“数字”已保存在数据库中的对象。

谢谢

parent引用的types必须与它引用的模型中_id的types相匹配。 所以,而不是Schema.Types.ObjectId它应该是String

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

你可以试试这个

 parent: [ this ] 

有用