用自顶向下的父引用填充树



正如我在另一个问题中所说的,我正在做一个涉及树的项目。

  • 树使用父引用,所以每个节点都有它的父节点的id
  • 我需要加载树自上而下(从根到子)从db和替换父引用的子数组(因为客户端需要它们)
  • 我选择了这种方法,因为我估计98%的操作是在节点上创建/更新(这样我只需要在更新上创建1个节点,而不是更新父节点以将子节点添加到数组中),只有大约2%的操作是读取操作(我只需要读取完整的树,没有读取部分或子树的用例)

树模型是:

const mongoose = require("mongoose");
const Promise = require("bluebird");
mongoose.Promise = Promise;
const Node = require("./node-model");
const TreeSchema = new mongoose.Schema({
  root: { type: Schema.Types.ObjectId, ref: 'Node' },
});

和Node模型:

const mongoose = require("mongoose");
const Promise = require("bluebird");
mongoose.Promise = Promise;
const NodeSchema = new mongoose.Schema({
  parent:  Schema.Types.ObjectId,
  children: [], // to be populated on loading the tree
  data: {
    d1: String, 
    //...
  }
});
NodeSchema.methods.populateTree = function() {
  return this.constructor.find({ parent: this._id }).exec()
    .then(function(arrayOfChildren) {
      return Promise.each(arrayOfChildren, function(child){
        this.children.push(child); // PROBLEM: 'this' is undfined here!
        delete child.parent; // delete parent reference because JSON has problems with circular references
        return child.populateTree();
      });
    });
}

还有一个树容器:

const TreeContainerSchema = new mongoose.Schema({
  owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  tree: { type: Schema.Types.ObjectId, ref: 'Tree' },
});

我试图加载完整的树(在他的容器)发送回客户端的JSON如下:

getTreeContainerById = function(req, res) {
  var promise = TreeContainer.
    findById(req.params.id).
    populate("owner", "name"). // only include name
    populate({
      path: "tree",
      populate: {
        path: "root",
        populate: "data"
      }
    }).exec();
    promise.then(function(treeContainer){
      return treeContainer.tree.root.populateTree()
        .then(function(){ return treeContainer });
    }).then(function(treeContainer) {
      // I need the tree container here to send it back to the client
      res.json(treeContainer);
    });
};

但是这个实现不起作用。我面临的问题是:

  • populateTree模式方法中,我无法通过"this"(未定义)访问当前节点,但我需要以某种方式将子节点添加到数组
  • 如果我尝试child.parent.children.push代替,这也不起作用,因为我只有父(在child.parent)的id,而不是实体(我不认为这是从数据库中再次加载它的正确方法)
  • 在较早的版本中,我遇到了这个问题,在树完全填充之前,JSON被发送回客户端,但我认为我通过使用模式方法解决了这个问题
  • 总的来说,我不知道,如果这是正确的方法来解决我的问题(填充子引用和删除父引用在我的树),或者如果有一个更合适的解决方案
我希望我能把我的问题说清楚。任何帮助都非常感激!

使用populateTree,如下所示:

NodeSchema.methods.populateTree = function() {
  var node = this;
  return this.constructor.find({ parent: this._id }).exec()
    .then(function(arrayOfChildren) {
      return Promise.each(arrayOfChildren, function(child){
        node.children.push(child);
        child.parent = null;
        return child.populateTree();
      });
    });
}

感谢@danh,他也提出了同样的建议!

最新更新