2014-09-24 43 views
2

我正在使用nodejs,貓鼬,我試圖通過父母建立一個shema包含對自己的引用。父應該是對DataType的引用。貓鼬與自己的ObjectId自我引用投擲:投到ObjectId失敗

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; 

每個數據類型都有自己的ID(不蒙戈產生的),我認爲這是它會導致問題的地方。它會拋出一個錯誤強制objectid在路徑「parent」的路徑上的值爲「Number」時失敗,其中Number是已保存在DB中的ID爲「Number」的對象。

感謝

回答

2

的類型parent引用必須在它所引用的模型_id的類型相匹配的。因此,而不是Schema.Types.ObjectId應該String

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

謝謝快速答覆。它正在工作,我可以在DB中看到它。只是想我是沒有像** ObjectID(「數字」)**只** **數字**的東西。我在MongoDB和nodejs中都很新,所以我不確定它應該是這樣的。 – 2014-09-24 13:59:23

+0

@ user2748323只要「數字」在集合中提供了唯一的'_id',那就完全正確了。 – JohnnyHK 2014-09-24 14:02:34

+0

有沒有辦法從貓鼬中直接得到**對象**樹?我想代替父母:_id get ** parent:[Object] ** – 2014-09-25 13:18:44

0

你可以試試這個

parent: [ this ] 

它的工作原理

+4

請在您的答案中添加更多詳細信息。 – 2016-03-24 14:30:35