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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With