2014-08-30 52 views
0

我正在使用Node(0.10.5)/ Mongo(2.4)/ Mongoose(3.6)來構建遊戲,並且我有一個像這樣的Mongoose模式。 。Mongoose模式 - 使用對象而不是數組作爲子文檔

var GameStateSchema = new Schema(
    { 
     buildings: { 
      // This object will contain buildings of the same structure, e.g. 
      // "1": {name: "cabin", x: 128, y: 0}, 
      // "2": {name: "lighthouse", x: 192, y: 64} 
      // It'll grow to several hundred buildings. 
     }, 
     nextId: 3 
    } 
); 

var BuildingSchema = new Schema(
    { 
     name: String, x: Number, y: Number 
    } 
); 

什麼是讓每個建築在buildings對象使用BuildingSchema最好的方法?我真的不想走下手工驗證一切的路線!

注意:buildings對象不是一個數組,例如, buildings: [BuildingSchema],因爲我聽說Mongo在大型數組中表現不佳(而且建築物的順序並不重要)。

+1

你是什麼意思驗證一切?此外,您無法在GameStateSchema中定義值,架構包含類型等,而不是數據。 – 2014-08-31 11:02:26

+0

通過「驗證」我的意思是檢查鑄造和'模式嚴格模式'寫入數據庫。不是更精細的Mongoose驗證方法。而上帝,是的,對不起,我忘記了數據線的評論!現在編輯。 – chichilatte 2014-09-01 12:45:56

+1

儘管您有異議,但您應該在這裏爲'buildings'使用一個數組。沒有問題。 – JohnnyHK 2014-09-01 19:15:14

回答

0

啊,答案很簡單。你可以使用相同的...

buildings: [BuildingSchema] 

對象以及數組的表示法。舉例來說,如果你添加一個新的建築...

GameStateSchema.update({$set: {"buildings.1": {name: "cabin", x:128, y: 0} }}) 

貓鼬將使用BuildingSchema,做的非常基本的(但重要)的驗證,例如,添加一個新的建設建築物只能有一個name,xy

如果您在$ set項目之前未明確創建buildings數組,它將默認爲對象。位反直覺,但很方便:)

編輯 - 我說得太快,結果通過Mongoose模型實例訪問buildings只適用於它是一個數組。問題依然存在。

相關問題