Mongoose.js:如何通过人口实现树结构

Eth*_*inn 7 javascript mongoose mongodb

我正在使用Mongoose 3.x来实现一个树结构(类似于Mongo文档中的这个结构),但是我不确定封装所有逻辑的最佳方法是通过其兄弟姐妹和祖先来加载特定节点,特别是如何最好地使用人口功能,其中ref与参考者在同一个集合中.

对于某些上下文,我正在使用的树是不编辑节点但可以随时向任何节点添加新子节点的树.到目前为止,我已经通过一组在初始查找后加载对象的模型方法正常工作,但似乎应该有一种更好的方法来轻松加载单个分支,其中包含我需要的所有父级和兄弟级数据控制器中的命令,并在模型上的一些方便的查找方法中封装所有相关的人口.

我试图使用的基本Schema可能是这样的(也可以在这里获得:https://gist.github.com/3889616):

// Sub-document to store parent ref along with it's value (a form of caching)
var Parent = new Schema({
    id: ObjectId
  , text: String
});

// Main tree-node element schema
var Branch = new Schema({
    text: {
        type: String
      , required: true }
  , date: {type: Date, default: Date.now }
  , trail: [Parent]
  , parentBranchId: ObjectId
  , parentBranch: { type: Schema.Types.ObjectId, ref: 'Branch' }
  , _children: [{type: Schema.Types.ObjectId, ref: 'Branch'}]
  // These two have been commented out because I have no clue how to best implement 
  // , _priorSiblings: { type: Schema.Types.ObjectId, ref: 'Branch' }
  // , _followingSiblings: { type: Schema.Types.ObjectId, ref: 'Branch' }
});
Run Code Online (Sandbox Code Playgroud)

我希望能够通过类似下面的代码来加载具有相关相关数据的分支,尽管此时我已经非常迷失并且可能是一个很好的基础:

  req.app.models.Branch
    .findById(req.param("id"))
    .populate("parentBranch")
    .populate("parentBranch._children")
    .exec(...)
Run Code Online (Sandbox Code Playgroud)

最终,我很想将一些东西抽象成Mongoose的"树"插件,但我想我必须首先正确地构建这个架构.有任何想法吗?

FWIW,在一天结束时,我真正需要的每个分支的数据是父母,下一个兄弟,以前的兄弟(在创建时间方面)和父母的所有孩子.

提前致谢!

小智 1

我知道这个问题很老了,但是您研究过猫鼬树模块吗?https://github.com/franck34/mongoose-tree

在我看来,它有一个非常好的 API 来处理对象之间的关系。