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

时间:2012-10-15 01:09:38

标签: javascript mongodb mongoose

我正在使用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' }
});

我希望能够通过类似下面的代码来加载具有相关相关数据的分支,尽管在这一点上我很丢失并且可能是一个很好的基础:

  req.app.models.Branch
    .findById(req.param("id"))
    .populate("parentBranch")
    .populate("parentBranch._children")
    .exec(...)

归根结底,我很想将一些东西抽象成Mongoose的“树”插件,但我想我必须首先正确地构建这个架构。有什么想法吗?

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

提前致谢!

1 个答案:

答案 0 :(得分:1)

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

它有一个非常好的API来处理对象IMO之间的关系。