简体   繁体   English

多次猫鼬查询后返回结果对象

[英]Return Results Object After Multiple Mongoose Queries

In Express I have an array of projects, with each project containing an array of workSessions stored as Mongo ObjectIds. 在Express中,我有一个项目数组,每个项目都包含一个存储为Mongo ObjectIds的workSessions数组。

I want to iterate over the array of projects, and for each project get its workSessions from MongoDB, then add the list of workSessions to an object which will end up containing all the workSessions from all the projects in the projects array. 我想遍历项目数组,并为每个项目从MongoDB中获取其workSessions,然后将workSessions列表添加到一个对象,该对象最终将包含projects数组中所有项目的所有workSessions。

projectService.GetWorkSessions(result.user._id)
  .then((projects) => {
    console.log(projects) // nothing gets logged.
  }

GetWorkSessions: (userId) => {
  return getProjects(userId) // this is ok.
    .then((projects) => {
      let workSessions = {};
      let counter = 0;
      return promise = new Promise((resolve, reject) => {
        return projects.forEach((project) => {
          return getWorkSessions(project)
            .then((sessionsList) => {
              counter ++
              workSessions[project._id] = sessionsList;
              if(counter == projects.length) {
                console.log('done')
                promise.resolve();
              }
            })
        })
      })
    })
},

The workSession object gets populated, but how do I return it to the calling function once the forEach has completed? workSession对象被填充,但是一旦forEach完成,如何将其返回给调用函数?

When you want to map an array of values to an array of asynchronously-retrieved values, use Promise.all(values.map(...)) : 如果要将值数组映射到异步检索的值数组,请使用Promise.all(values.map(...))

const projectWithSessions = (project) =>
    getWorkSessions(project).then((sessions) => 
        ({ project, sessions })
    );

GetWorkSessions: (userId) => 
    getProjects(userId).then((projects) => 
        Promise.all(projects.map(projectWithSessions))
    );

The return value of GetWorkSessions() should resolve to an array of objects each with a .project and .sessions property. GetWorkSessions()的返回值应解析为一个对象数组,每个对象均具有.project.sessions属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM