首页 > 解决方案 > Mongo DB 在数组中返回未定义的值

问题描述

我有这段代码,它在 MongoDB 中获取一周中给定日期的文档数量的值。作为返回请求,“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;
}

在这种情况下,当我在阵列控制台中发出请求时。我得到这个回报:

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

命令返回console.log(week);

命令返回

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

console.log(qweek[1]);

日志输出:

undefined

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

命令返回

我想知道为什么价值会伴随着undefined.

标签: javascriptmongodbundefined

解决方案


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

简短说明: mongo-db 查询调用async本质上是执行,不会等待它完成,然后再到达块console.log(qweek)外。then结果,您将得到qweek空 [] 或qweek[1]未定义。

解决这个问题的几种方法是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);
  });

推荐阅读