How to traverse nested document recursively in Mon

2020-06-04 04:08发布

问题:

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({
    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.

Thanks in Advance.

回答1:

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!