Skip to content

Instantly share code, notes, and snippets.

@khanhney
Created December 2, 2019 08:12
Show Gist options
  • Select an option

  • Save khanhney/10857c97f02bb70f350adf55a361bd9a to your computer and use it in GitHub Desktop.

Select an option

Save khanhney/10857c97f02bb70f350adf55a361bd9a to your computer and use it in GitHub Desktop.
mongoose recursive without support op mongoose
const mongoose = require('mongoose');
const bluebird = require('bluebird');
const User = require('./model');
mongoose.Promise = bluebird;
constructPopulateConfigObj = (level, path) => {
const oneLevel = () => ({ path });
let obj = oneLevel();
while (level) {
if (level !== 1) {
obj.populate = Object.assign({}, obj);
}
obj = Object.assign({}, obj);
--level;
}
return obj;
};
require('./db')().then(() => {
console.log('Connected!');
User.find({ name: 'User5' }, { _id: 0, level: 1 })
.then(resp => {
const { level } = resp[0];
return User.find({ name: 'User5' }).populate(
constructPopulateConfigObj(level, 'friends')
);
})
.then(resp => console.log(JSON.stringify(resp)));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment