How to recursively move a subdocument in MongoDB

I am trying to transition recursively to nth node in the 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 do not know how to generate a tree similar to a structure from this model, any ideas on how to implement this? I use Mongoose for the model, and also tried a deep tree and the filling did not work. only works for the first level.

Thanks at Advance.

+5
source share
1 answer

The easiest way is to use bluebird promises, in particular the each , props , reduce and map methods, depending on your use case.

In your case, I would suggest something line by line

 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, eg getUser(rootUserObjectId) .then(function(userTree){ console.log(userTree) }) 

Let me know how this happens!

+4
source

All Articles