Class: TreeDocument

mongodb/models/lib/treeDocument~TreeDocument

(abstract) new TreeDocument(top_level_node, branches, optionsopt)

Abstract class to generalize commonly-used tree-traversal queries & other tree-oriented utilities for Mongo collections containing arbitrary levels of nested documents.

Since Mongo encourages storage of "flattened" or "normalized" documents, accessing highly nested documents via Mongoose's built-in query tools can be a bit tricky, so this is an attempt to generalize what can be generalized so you don't have to rewrite the same stupid query functions for each document tree you write.

Couple of key assumptions about how your data is structured:

  1. One document in top-level node collection per tree
  2. Child models are stored in document arrays under each parent
  3. Child model document arrays are keyed by PLURALIZED, LOWERCASED MODELNAME, i.e. model = Placement ==> { placements: [array of placements }
Parameters:
Name Type Attributes Description
top_level_node String

top-level model name

branches Array

list of all branches in tree, not including top node. Each branch is a list of mongoose models ordered from highest to lowest order

options Object <optional>

options object

Properties
Name Type Attributes Default Description
read String <optional>
'secondary'

mongoose read variable. Default is 'secondary' which allows queries against slave DB.

Source:

Methods

getChildDocument(objectId, modelName, parentDoc, callback)

Gets nested document by ObjectId any number of levels deep in a document tree, given an existing parent-level document.

NOTE: Returned object will also contain keys of the form 'parent_[model]', which contain the child's parent object at a specific level of the tree.

Seems kind of silly that this functionality doesn't exist in Mongoose, but I looked for a while and got frustrated so I wrote it myself.

Parameters:
Name Type Description
objectId
modelName
parentDoc
callback
Source:

getNestedObjectById(objectId, modelName, populateopt, callback)

Gets nested document by ObjectId any number of levels deep in a document tree.

Really just queries on nested ID to find parent document, and then loops recursively over all children of that parent document to only return the desired child.

NOTE: Returned object will also contain keys of the form 'parent_[model]', which contain the child's parent object at a specific level of the tree.

Seems kind of silly that this functionality doesn't exist in Mongoose, but I looked for a while and got frustrated so I wrote it myself.

Parameters:
Name Type Attributes Description
objectId
modelName
populate <optional>

fields to populate in document. Space delimited string of paths, or array of paths. Passed to model.deepPopulate

callback
Source: