How does nodejs mongodb express merge two one-to-many tables into a json object to return

  node.js, question

It is the first time to use nodejs mongodexpress as a project.
Two tables, departments and personnel. There is an attribute storage department id in the personnel.

Now I want to spell the results of these two tables into the following format and return them to the browser:

[
 bracket
 Name:' department name',
 People:[ personnel object array]
 },
 {Second Department}
 ...
 bracket

First find out all departments and get the array of all departments in the callback, but then there is no way. The personnel array found according to the department must be obtained in the callback queried by the lower level. I can’t think of any way to add it to the department array recalled by the higher level.

(pseudocode)
 Db.department.find ({}, function (err, objs1) {
 for(let i of objs1){
 Db.personnel.find ({department id:i._id},function(err,objs2){
 i.people=objs2;
 //Because of the asynchronous problem, it is obviously useless to modify objs1 here, and then I can't think of what to do.
 });
 bracket
 res.send(objs1);
 })

Also checked a lot of things, promise, generator, async, also wrote the function test, but for the api that the database comes with, he is using the original asynchronous callback method, take him can find no way out
How to deal with it?

There are two methods, one is to use mongooserefTo organize department data, another method is to read department and personnel information respectively, and then assemble the data after corresponding.

Useref

In the personnel’sSchemaInside, make the following settings:

var PeopleSchema = new mongoose.Schema({
 depart: {
 type: mongoose.Schema.ObjectId,
 ref: 'Depart'
 bracket
 });

Then, when obtaining personnel information, use thepopulateMethods:

People.find().populate('depart').exec(function(err, docs){
 //  ...
 });

You can print the structure and look at the specific data organization.

Respectively inquire and reassemble

The approximate implementation code is as follows:

var peoples = null, departs = null, flag = 0;
 
 People.find().exec(function(err, docs){
 if(err) {
 // handle error
 bracket
 peoples = docs;
 Goon (plus flag);
 });
 
 Depart.find().exec(function(err, docs){
 if(err) {
 // handle error
 bracket
 
 departs = docs;
 Goon (plus flag);
 });
 
 function goon() {
 if(2 !  == flag) return;
 
 //organize your data with peoples and departs
 bracket