JPB
JPB

Reputation: 41

Mongoose Nested Arrays, Trees and Embedded Docs

I have a mongoose schema like this:

Schema: Item
Schema: SubItem
Schema: SubItemTwo

//Item Schema looks like this:
Item: {
   SubItem: [SubItemSchema]
}

SubItemSchema looks like this:
{
  field1: String,
  field2: String,
  OtherItems: [SubItemTwoSchema]
}

SubItemTwoSchema is a flat schema of some string fields.

Basically I have found it pretty much impossible to work with SubItemSchema.OtherItems using queries, $set, $inc and $addToSet operators etc. I don't believe that the mongoose approach is efficent as I have to basically save the entire "Items" instance after marking the subarrays as modified i.e Mongoose push() and save() i.e Item.SubItem[0].OtherItems.push(thing)

Mongoose only supports an array of embedded documents and for an array within an array - it becomes impossible to do much with the second level array.

So my question is what approaches are people using to work this type of data model i.e. an object with an array that has a sub-array. I note the documentation at http://docs.mongodb.org/manual/tutorial/model-tree-structures/ regarding tree structures but I have yet to see any implementation of how to model a 2 level nested array without using mongoose's push approach. The MongoDb document on modelling tree structures requires adding fields to reference parents and ancestors but this seems overkill since my tree is only 3 levels deep.

So should I: 1. Be using document arrays 2. Doing away with mongoose and using embedded documents that are not in an array 3. Re-modelling my data so that I dont have an array within an array?

If option 3 is the answer how would you suggest remoddeling the schemas so that SubItemTwo docs can be children of SubItem docs and that SubItem docs can be children of a parent Item.

Thanks

Upvotes: 2

Views: 2491

Answers (1)

Marius
Marius

Reputation: 185

I solved it by implementing schema with array of parents included in children. Does the job for me. Here is the implementation as a module: https://github.com/mariuskubilius/lbg-mongoose-utils/blob/master/lib/ancestorTree.js

It's implemented using this way: http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/

If you need some clarifications do not hesitate to ask.

Upvotes: 2

Related Questions