使用Mongoose检索文档的所有祖先

时间:2018-05-18 11:06:08

标签: javascript node.js mongodb express mongoose

这个问题的要点是要知道如何使用Mongoose正确检索文档的所有祖先。我正在使用this Model Tree Structures with an Array of Ancestors

db.categories.insert( { _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" } )
db.categories.insert( { _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" } )
db.categories.insert( { _id: "Databases", ancestors: [ "Books", "Programming" ], parent: "Programming" } )
db.categories.insert( { _id: "Languages", ancestors: [ "Books", "Programming" ], parent: "Programming" } )
db.categories.insert( { _id: "Programming", ancestors: [ "Books" ], parent: "Books" } )
db.categories.insert( { _id: "Books", ancestors: [ ], parent: null } )

以下是我正在做的事情,我正在尝试遍历nextParent并在调用parentCategory.parent后将结果ancestors.unshift(nextParent)分配到其中,但遗憾的是它无法按预期工作由于parentCategory.parent是异步的,因此model.findOne()未分配:

const { parent } = req.body;
...
const ancestors = [];
let nextParent = parent;

while (nextParent) {
  model.findOne(
    { _id: nextParent },
    (err, parentCategory) => {
      assert.ifError(err);

      if (parentCategory) {
        ancestors.unshift(nextParent);
      }
      nextParent = parentCategory ? parentCategory.parent : false;
    }
  );
}

是否有正确的方法来检索文档的所有祖先?如果我做得很好,我已经做了这个修改:

const ancestors = [];
let nextParent = parent;

while (nextParent) {
  let parentCategory = await model.findOne( { _id: nextParent } );

  if (parentCategory) {
    ancestors.unshift(nextParent);
  }
  nextParent = parentCategory ? parentCategory.parent : false;
}

我现在正在SyntaxError: Unexpected identifier - > let parentCategory = await **model.findOne(...)**。对此有何解决方案?

0 个答案:

没有答案