如何在函数内使用db.collection.find并返回结果

时间:2019-03-25 21:22:40

标签: javascript node.js mongodb-query

我正在尝试调用此函数,并期望获得“赢家”数组。相反,我得到一个空数组。

我想它与异步/等待问题有关。

感谢您的帮助!


这是代码:

function calculate() {

    var results = [];
    var result = [];
    var winners = [];
    var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');
    var url = 'mongodb://..........';

    MongoClient.connect(url, function (err, db) {
      var cursor = db.collection('answers').find();
      cursor.forEach(function (doc) {
        results.push(doc);
      }, function () {
        for (let n = 0; n < 8; n++) {
          for (let r = 0; r < results.length; r++) {
            result.push(results[r][n]);
          }
          winners.push({
            [n]: winnerCalculate(result)
          });
          result = [];
        };
        winners = Object.assign({}, ...winners);
        winners.date = new Date();
        db.collection('winners').insertOne(winners);
        // res.redirect('/thanks');
        console.log(winners);
        db.close();
      });
      return winners;
    });


0 个答案:

没有答案