Mongoose / Mongodb数据库调用以不一致的顺序返回数据

时间:2018-04-09 21:35:21

标签: javascript node.js mongodb asynchronous mongoose

我正在查询两个不同的集合。第一个包含我要查找的大部分数据,包括链接到第二个集合的_id。使用此_id,我想在第二个集合中搜索正确的文档并获取Name值。

我遇到的问题是2倍(1比其他重要得多)。

1 - 首次加载呼叫的页面时,效果很好。如果我刷新页面,并在所有后续刷新,它将失败。当我第二次记录元素和索引时,我将获得正确的对象,但索引将被反转(1,0而不是0,1),并且不会从api调用返回任何内容。我想知道为什么会这样,以及任何解决方法。

2 - 这是一个小得多的问题。如果我更改allStudents[i].Teacher = teacherData.Name;替换现有字段的值,那么它可以正常工作。但是,如果我将其更改为allStudents[i].TeacherName = teacherData.Name;,这会向对象添加新字段,那么它将根本不添加任何内容。我不明白为什么我无法向对象添加新字段,即使我之前从未遇到过这方面的问题?

export const getAllStudents = (req, res) => {
  Student.find(
    { UserType: "STUDENT" },
    req.query.fields    
  )
  .then(data => {
    console.log('line 34')
    if (data) {
      let allStudents = [];
      data.forEach((e, i) => {
        console.log('line 38', e.Teacher);
        Teacher.findOne(
          { _id: e.Teacher },
          'Name'
        )
        .then(teacherData => {
          console.log('line 44', e, i === data.length - 1)
          allStudents.push(e);
          if (studentData && i !== data.length - 1) {
            allStudents[i].Teacher = teacherData.Name;
          } else if (partnerData) {
            allStudents[i].Teacher = teacherData.Name;
            console.log('line 50')
            res.json({ data: allStudents }).status(200);
          } else res.json({ message: "No Teacher is associated with this user." }).status(401);
        })
        .catch(err => res.json({ message: "No Teacher is associated with this user." }).status(401));
      })
    } else res.json({ message: "No student could be found." }).status(401);
  })
  .catch(err => res.json({ message: "No student could be found." }).status(401));
}

console.log输出如下:

[0] line 44 { _id: 5ab94d69418a5132507d5b41,
[0]   FirstName: 'PersonA',
[0]   LastName: 'Lastname',
[0]   Email: 's@example.ca',
[0]   Teacher: '5ab94d69418a5132507d5b60' } 0 false
[0] line 44 { _id: 5ab94d69418a5132507d5b42,
[0]   FirstName: 'PersonB',
[0]   LastName: 'Lastname',
[0]   Email: 'student@example.com',
[0]   Teacher: '5ab94d69418a5132507d5b60' } 2 true
[0] line 44 { _id: 5ab94d69418a5132507d5b39,
[0]   FirstName: 'PersonC',
[0]   LastName: 'Lastname',
[0]   Email: 'a@exmple.ca',
[0]   Teacher: '5ab94d69418a5132507d5b59' } 1 false

1 个答案:

答案 0 :(得分:0)

我通过创建两个基本的api调用解决了这个问题,然后在我的Redux Action中组织了数据。