Mongoose schema – using an Object instead of an Array for subdocuments Mongoose schema – using an Object instead of an Array for subdocuments mongoose mongoose

Mongoose schema – using an Object instead of an Array for subdocuments


Ahh, the answer is simple. You can use the same...

buildings: [BuildingSchema]

notation for objects as well as arrays. For instance, if you add a new building...

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

Mongoose will add a new building using the BuildingSchema, doing very basic (but vital) validation, e.g. a building can only have a name, x and y.

If you don't create a buildings array explicitly before you $set items, it will default to being an object. Bit counter-intuitive but very handy :)

EDIT – I spoke too soon, turns out accessing buildings via a Mongoose model instance only works when it's an array. The question still stands.