Created
December 2, 2019 08:12
-
-
Save khanhney/10857c97f02bb70f350adf55a361bd9a to your computer and use it in GitHub Desktop.
mongoose recursive without support op mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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