2012-02-18 94 views
19

我想引用在節點模型另一個對象,MongoDB的類型參考節點

User = new Schema({ 
     username: { 
      type: String, 
      index: {unique: true} 
     } 
}); 

Idea = new Schema({ 
     Creator: { 
      type: User 
     } 
}); 

,但我得到這個錯誤Undefined type at "creator" Did you try nesting Schemas? You can only nest using refs or arrays.我相信我要用裁判,但它無法找到文檔,可一些一個幫助我。謝謝

回答

34

我在這裏發現了我自己的問題的答案。

User = new Schema({ 
    username: { 
     type: String, 
     index: {unique: true} 
    } 
}); 

Idea = new Schema({ 
    Creator: { 
     type: Schema.ObjectId, 
     ref: 'User' 
    } 
}); 
+1

1.救命2.「mongoose.Types.ObjectId」和「mongoose.Schema.ObjectId」有什麼區別?我發現它真的很混亂,它觸發「未定義類型」的錯誤,它很難理解爲什麼 – 2013-12-05 14:22:17

+0

我想知道 的差異mongoose.Types.ObjectId VS mongoose.Schema.ObjectId太! – sunnycmf 2014-02-16 14:47:01

0

這是link手動@ refs。

您無法在架構設計級別使用參考。

16

我想回答這個問題,因爲這是Google的第一個結果。

不,您不能使用嵌套架構作爲其他答覆說。但是你仍然可以在不同的模式中使用同一個對象。

// Regular JS Object (Not a schema) 
var Address = { 
    address1: String, 
    address2: String, 
    city: String, 
    postalcode: String 
}; 

var Customer = new Schema({ 
    firstname: String, 
    lastname: String, 
    address: Address 
}); 

var Store = new Schema({ 
    name: String, 
    address: Address 
}); 

這樣,你可以修改地址對象,以使在所有模式共享對象中的可用的變化。