Mongo DB returns 数组中的未定义值

Mongo DB returns undefined values in an array

我有这段代码,它获取 MongoDB 中一周中给定日期的文档数量值。作为 return 请求,"qweek" 数组被填充。

function dates(current) {
  var week = new Array();

  // Starting Monday not Sunday
  current.setDate((current.getDate() - current.getDay() + 1));

  for (var i = 0; i < 7; i++) {
    var dd = String(current.getDate()).padStart(2, '0');
    var mm = String(current.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = current.getFullYear();
    var day = dd + '/' + mm + '/' + yyyy;

    week.push(day);

    current.setDate(current.getDate() + 1);
  }

  return week;
}

// Initialize the App Client
const client = stitch.Stitch.initializeDefaultAppClient("app-id");

// Get a MongoDB Service Client
const mongodb = client.getServiceClient(
  stitch.RemoteMongoClient.factory,
  "mongodb-atlas"
);

//projection config
const options = { // Match the shape of RemoteFindOptions.
  limit: 1000, // Return only first ten results.
  projection: { // Return only the `title`, `releaseDate`, and
    day: 1, //   (implicitly) the `_id` fields.
  },
  sort: { // Sort by releaseDate descending (latest first).
    releaseDate: -1,
  },
}

// Get a reference to the travels database
const db = mongodb.db("travels");

function displayCountTravels() {
  var daysweek = dates(new Date());
  var qweek = new Array();

  for (var l = 0; l < daysweek.length; l++) {
    db.collection("details")
      .find({
        "day": daysweek[l]
      }, options)
      .toArray()
      .then(docs => {
        qweek.push(docs.length);
      });
  }

  console.log(qweek);
  console.log(qweek[1]);

  return qweek;
}

在这种情况下,当我在阵列控制台中发出请求时。我明白了 return:

console.log(qweek);
Log output:[]
0: 0
1: 0
2: 0
3: 2
4: 0
5: 0
6: 0
length: 7
__proto__: Array(0)

Return 命令 console.log(week);

但是当我尝试通过索引获取值时。数组项 return 未定义。

console.log(qweek[1]);

日志输出:

undefined

Return 命令 console.log(week[1]);

我想知道为什么这个值带有undefined

本质上这是 Javascript 中 asynchronous 行为的一个例子。最重要的是 asynchronous 调用是在 for..loop.

中进行的

简短说明: mongo-db 查询调用本质上是 async,执行不会在到达之前等待它完成console.log(qweek)then 块之外。结果,您将得到 qweek as empty[] 或 qweek[1] as undefined.

有两种方法可以解决此问题,即 Serializing with promises and async/await 或使用 Promise.all()。建议您阅读它们以了解更多信息。

使用async/await:语法更简洁且易于理解

async function displayCountTravels() {
  var daysweek = dates(new Date());
  var qweek = [];
  try {
    for (var l = 0; l < daysweek.length; l++) {
      /*wait for the promise to resolve before next iteration*/
      var docs = await db
        .collection("details")
        .find({ day: daysweek[l] }, options).toArray();

      qweek.push(docs.length);
    }
  } catch (e) {
    console.error(e);
  }

  console.log(qweek);
  console.log(qweek[1]);

  return qweek;
}

使用Promise.all(...):

function displayCountTravels() {
  var daysweek = dates(new Date());
  var promises = [];

  /*each mongo query is a promise, collect and return*/

  for (var l = 0; l < daysweek.length; l++) {
    promises.push(
      db.collection("details").find({ day: daysweek[l] }, options).toArray()
    );
  }

  return Promise.all(promises);
}

/*Calling fn, getting results in then since Promise.all() itself is promise*/
displayCountTravels()
  .then((results) => {
    /*using map to get lengths of the documents returned and put it in qweek*/
    var qweek = results.map((e) => e.length);
    console.log(qweek);
    console.log(qweek[1]);
  })
  .catch((e) => {
    console.error(e);
  });