nodejs mongodb express如何将一对多的两个表合并为一个json对象返回


第一次用nodejs mongodb express做项目
两个表,部门、人员。人员里面有一个属性存放部门id

现在想将这两个表的结果拼成如下格式返回给浏览器:


 [
        {
            name:'部门名称',
            people:[人员对象数组]
        },
        {第二个部门}
        ...
    ]

首先查出所有的部门,在回调里面获得到了所有部门的数组,但是接下来就没办法了,根据部门查找到的人员数组必须在下级查询的回调里面才能获得,想不到什么办法可以用来添加到上级回调的部门数组里面。


 (伪代码)
    db.部门.find({},function(err,objs1){
        for(let i of objs1){
            db.人员.find({部门id:i._id},function(err,objs2){
                i.people=objs2;
                //由于异步的问题,在这里修改objs1显然是没用的,然后就想不到该怎么做了
            });
        }
        res.send(objs1);
    })

也查了很多东西,promise、generator、async,也自己写了函数试验,但是对于数据库自带的api,他就是用的原始的异步回调的方式,拿他没辙啊
求教改如何处理?

express.js node.js mongodb

下一站蛋定 9 years, 3 months ago

有两个方法,一是使用 mongoose 的 ref 来组织部门数据,另外一个办法是分别读取部门和人员信息,再对应后组装数据。

使用 ref

在人员的 Schema 里,做如下的设置:


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

然后,在获取人员信息的时候,使用 populate 方法:


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

你可以打印一下结构看一下具体的数据组织。

分别查询再组装

大概实现的代码如下:


 var peoples = null, departs = null, flag = 0;

People.find().exec(function(err, docs){
  if(err) {
    // handle error
  }
  peoples = docs;
  goon(++flag);
});

Depart.find().exec(function(err, docs){
  if(err) {
    // handle error
  }

  departs = docs;
  goon(++flag);
});

function goon() {
  if(2 !== flag) return;

  //organize your data with peoples and departs
}

hhh2000 answered 9 years, 3 months ago

Your Answer