Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse nested document recursively in MongoDB

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.

like image 304
Crazy Chuck Avatar asked Sep 01 '15 18:09

Crazy Chuck


1 Answers

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!

like image 186
Yuri Zarubin Avatar answered Oct 04 '22 13:10

Yuri Zarubin