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