将 MongoJS select 结果保存到 NodeJS 中的数组,然后修改它

Saving MongoJS select result to an array in NodeJS and then modifying it

很难在 NodeJS 中保存和修改 MongoJS 查询的结果。

router.post('/getMySubjects', function (req, res) {
    var data = [];
    if (req.body.type == 'Professor') {
        db.subjects.find({ contractorID: req.body.userId }, function (err, subjects) {

            data = subjects;                    // SUBJECTS ARE NOW SAVED TO DATA SUCCESSFULLY

            data.forEach(function(subject) {
                db.faculties.find({ _id: mongojs.ObjectID(subject.subjectFor_faculty)}, function (err, faculty) {
                    subject.faculty = faculty;  // BUT HERE I WANT TO ADD A FACULTY (object)
                                                // BASED ON THE subjectFor_faculty (id) 
                                                // WHICH IS LOCATED IN EVERY (subject)
                                                // ELEMENT IN DATA ARRAY
                });
            });
            res.send(data);                     // THE DATA HERE IS UNMODIFIED
                                                // SAME AS DATA ON LINE 6 
        }); 
    }
});

我想我还没有完全理解响应是如何工作的(顺便说一句,应用程序是用 express 框架制作的),因为当数据第一次保存在第 6 行时,下一步就是发送数据,并且然后应用程序进入 forEach 循环...

您正在进行异步 mongo 查询。您必须让它们同步工作才能获得正确的数据。这是使用承诺的实现。

router.post('/getMySubjects', function (req, res) {
var data = [];
if (req.body.type == 'Professor') {
    db.subjects.find({ contractorID: req.body.userId }, function (err, subjects) {
        data = subjects;
        var promises = [];
        data.forEach(function(subject) {
          var promise = new Promise(function(resolve, reject) {
            db.faculties.find({ _id: mongojs.ObjectID(subject.subjectFor_faculty)}, function (err, faculty) {
                resolve(faculty);
            });
          });
          promises.push(promise);
       });
        Promise.all(promises).then(function(values){ 
           for(var i = 0; i< values.length;i++){
            data[i].faculty = values[i];               
           }
           res.send(data);
        });                  
    }); 
  } 
});