gpt4 book ai didi

javascript - 无法将 db.countDocuments 中的数据存储在 mongoDB 中

转载 作者:行者123 更新时间:2023-11-30 23:56:25 26 4
gpt4 key购买 nike

我对 Javascript 还很陌生,我不明白为什么我无法保存下面这段代码的结果。我正在使用 MongoDB,我想存储集群中的文档数量,以便我可以跟踪集群中有多少文档,但是,当我尝试在第三行记录输出时,它是未定义的。这是为什么?

let theIndex;
collection.countDocuments({}).then(res => theIndex = res);
console.log(theIndex);

最佳答案

collection.countDocuments({}) 返回一个 promise ,因此您应该在解析后使用 console.log:

collection.countDocuments({}).then(res => {
theIndex = res;
console.log(theIndex);
});

一旦 Promise 解析,.then 中的回调函数就会被执行。在回调之外记录它是行不通的,因为 console.log 行会立即执行,并在稍后的时间点(因为到达数据库等需要时间)调用回调。

请注意,即使 Promise 立即解析(尽可能快),由于 javascript 中的事件循环,回调仍然会稍后执行。

关于javascript - 无法将 db.countDocuments 中的数据存储在 mongoDB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com