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

2023-12-27

我正在尝试递归遍历 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 作为模型,并且还尝试了深层树和填充没有成功,因为它仅适用于第一级。

提前致谢。


最简单的方法是使用 bluebird Promise,特别是each, props, reduce and 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, 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)
  })

让我知道进展如何!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MongoDB 中递归遍历嵌套文档 的相关文章

随机推荐