【问题标题】:How to traverse nested document recursively in MongoDB如何在MongoDB中递归遍历嵌套文档
【发布时间】:2015-11-27 02:19:48
【问题描述】:

我正在尝试递归遍历 MongoDB 模型中的第 n 个节点。这是我的用户模型。

用户模型

var UserSchema  = new Schema({
    firstname : { type: String},
    parents:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    children:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    partner:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    sibling:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
});

我不知道如何从这个模型中生成树状结构,关于如何实现这个的任何想法?我正在使用 Mongoose 作为模型并且还尝试了深度树和填充没有成功仅适用于第一级。

提前致谢。

【问题讨论】:

  • 您有填充文档的示例吗?
  • 在这种情况下,尝试执行多于一个级别的人口的主要问题是,当一个用户有一个 parents 值引用另一个用户并且该用户有一个 children 值引用第一个用户。如果您尝试以递归方式自动填充它,您将创建一个无限循环。如果您要从一个孩子开始,然后沿着树向上显示所有父母,那么您应该是安全的,但您仍然需要跟踪所有 userId 以确保您没有意外用户自己的祖先。

标签: node.js mongodb mongoose


【解决方案1】:

最简单的方法是使用 bluebird Promise,特别是 eachpropsreducemap 方法,具体取决于您的用例。

在你的情况下,我会建议一些类似的东西

var bluebird = require('bluebird');
var mongoose = require('mongoose');
var UserModel = mongoose.model('User');

function getUser(userId) {
  return UserModel.findOne({_id: userId}).lean().exec()
    .then(function(user){
      return bluebird.props({
        firstName: user.firstName,
        parents: bluebird.map(user.parents, getUser),
        children: bluebird.map(user.children, getUser),
        partner: bluebird.map(user.partner, getUser),
        sibling: bluebird.map(user.sibling, getUser)
      })
    });
}

// Then call getUser once on the root node, e.g.
getUser(rootUserObjectId)
  .then(function(userTree){
    console.log(userTree)
  })

让我知道这是怎么回事!

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 1970-01-01
    • 2011-11-10
    • 2020-05-20
    • 2014-11-02
    • 2021-10-30
    • 2011-09-08
    • 2019-12-08
    • 1970-01-01
    相关资源
    最近更新 更多