简体   繁体   English

如何在MongoDB中递归遍历嵌套文档

[英]How to traverse nested document recursively in MongoDB

I'm trying to traverse recursively to the nth node in a MongoDB model. 我试图以递归方式遍历MongoDB模型中的第n个节点。 Here is my user Model. 这是我的用户模型。

User Model 用户模型

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' }],
});

I don't know how to generate a tree like structure from this model, any ideas on how to implement this ?, I'm using Mongoose for the model and also tried deep tree and populate didn't worked out as it works only for the first level. 我不知道如何从这个模型中生成一个类似树的结构,关于如何实现这个的任何想法?,我使用Mongoose作为模型,并且尝试深度树和填充没有解决,因为它只适用于第一级。

Thanks in Advance. 提前致谢。

The easiest way is to do this is to use bluebird promises, specifically the each , props , reduce and map methods, depending on your use case. 最简单的方法是使用bluebird promises,特别是eachpropsreducemap方法,具体取决于你的用例。

In your case, I'd suggest something along the lines of 在你的情况下,我会提出一些建议

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)
  })

Let me know how that goes! 让我知道这是怎么回事!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM