javascript - Mongoose .js : How to Implement Tree Structure via Population

标签 javascript mongodb mongoose

我正在使用 Mongoose 3.x 实现一个树结构(类似于 Mongo 文档中的这个),但我不确定封装所有逻辑以加载特定节点及其兄弟节点的最佳方式和祖先一般,特别是如何最好地使用 ref 与 ref-er 位于同一集合中的人口功能。

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

然后,我尝试使用的基本架构可能是这样的(也可在此处获得: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,归根结底,我真正需要的每个分支的数据是父级、下一个兄弟级、前一个兄弟级(都在创建时间方面)和父级的所有子级。

提前致谢!

最佳答案

我知道这个问题很老了,但是你有没有研究过 mongoose-tree 模块? https://github.com/franck34/mongoose-tree

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

关于javascript - Mongoose .js : How to Implement Tree Structure via Population,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12888103/

相关文章:

javascript - 通过仅使用 javascript 从文本框中的用户输入在 html 表中添加和删除行

javascript - 声明返回其变量值的技术限制是什么?

python - MongoDB 和 PyMongo - 如何在单个文档字段中连接字符串

java - 使用聚合读取时,Mongodb java 驱动程序会自动将日期转换为本地计算机时区

node.js - MongoError : Mod on _id not allowed

在 Mongoose 中将属性定义为 ObjectId 时出现 typescript 错误

javascript - 如何使用 Node 请求模块正确编码表情符号?

javascript - Angular 指令获取 "Synchronous XMLHttpRequest on the main thread is deprecated"

node.js - Elastic Beanstalk nginx 代理抛出 502 Bad Gateway

javascript - Node.js - 如何创建可以访问根路径 "/'之前的url的请求