如何在MongoDB中递归遍历嵌套文档 [英] How to traverse nested document recursively in MongoDB

查看:156
本文介绍了如何在MongoDB中递归遍历嵌套文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图递归遍历MongoDB模型中的第n个节点.这是我的用户模型.

I'm trying to traverse recursively to the nth node in a MongoDB model. Here is my 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' }],
});

我不知道如何从该模型生成树状结构,有关如何实现此结构的任何想法?,我在模型中使用Mongoose,还尝试了深层树并填充,因为它不起作用仅适用于第一级.

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.

预先感谢.

推荐答案

最简单的方法是使用bluebird promises,具体来说是eachpropsreducemap方法,具体取决于在您的用例上.

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.

在您的情况下,我建议采取类似的措施

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

让我知道怎么回事!

这篇关于如何在MongoDB中递归遍历嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆