node.js – 如何在MongoDB中递归遍历嵌套文档

前端之家收集整理的这篇文章主要介绍了node.js – 如何在MongoDB中递归遍历嵌套文档前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图以递归方式遍历MongoDB模型中的第n个节点.这是我的用户模型.

用户模型

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

我不知道如何从这个模型中生成一个类似树的结构,关于如何实现这个的任何想法?,我使用Mongoose作为模型,并且尝试深度树和填充没有解决,因为它只适用于第一级.

提前致谢.

解决方法

最简单的方法是使用bluebird promises,特别是每个,props,reduce和map方法,具体取决于你的用例.

在你的情况下,我会提出一些建议

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,partner: bluebird.map(user.partner,sibling: bluebird.map(user.sibling,getUser)
      })
    });
}

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

让我知道这是怎么回事!

猜你在找的Node.js相关文章