javascript - 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
.
解决方案
本质上,这是asynchronous
Javascript 中的一个行为案例。最重要的是,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);
});
推荐阅读
- matlab - 使用文件和附加参数启动 matlab
- kubernetes - 防止停止来自 Kubernetes pod 的日志记录
- javascript - 如何实现在网页向下滚动时加载新文章地址栏更改网址
- python - 网格中的 Numpy 独特三角形
- directory - 使用目录作为输出时的 Snakemake SyntaxError
- javascript - getaddrinfo ENOTFOUND www.google.com www.google.com:80
- yaml - 覆盖 from_yaml 以添加自定义 YAML 标记
- go - 在选择中使用子查询
- wordpress - WordPress 上的 ACF PRO 和 Google 地图
- symfony - Symfony 4:FMElfinderBundle 上传图片空白页