How to traverse nested document recursively in MongoDB

后端 未结 1 652
既然无缘
既然无缘 2021-02-09 19:47

I\'m trying to traverse recursively to the nth node in a MongoDB model. Here is my user Model.

User Model

var UserSchema  = new Schema({         


        
1条回答
  •  忘了有多久
    2021-02-09 20:16

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

    Let me know how that goes!

    0 讨论(0)
提交回复
热议问题