[英]Pushing mongoDB results to an array, but the array remains empty
This is my first question on stack overflow, so bear with me.这是我关于堆栈溢出的第一个问题,请耐心等待。
So I have a controller function that is rendering my google maps api, and I am trying to loop through the results from mongoDB and push them to an array so that I can pass it to a script tag on the ejs.所以我有一个控制器函数来渲染我的 google maps api,我试图遍历来自 mongoDB 的结果并将它们推送到一个数组,以便我可以将它传递给 ejs 上的脚本标记。 I am able to console.log(myArr) within the for loop and get results, but not outside of it (just above the res.render).我能够在 for 循环中使用 console.log(myArr) 并获得结果,但不能在循环之外(就在 res.render 之上)。 I am assuming my that my problem is my result within res.render is receiving an empty array.我假设我的问题是我在 res.render 中的结果正在接收一个空数组。
Please help me I have been stuck on this problem for days now.请帮助我我已经被这个问题困扰了好几天了。 Thank you, Andrew谢谢你,安德鲁
function showMap(req, res) {
let myArr = [];
db.collection("poppies").find().toArray(function (err, result) {
for (let i = 0; i < result.length; i++) {
myArr.push(result[i].Address);
};
});
res.render('map', {
result: JSON.stringify(myArr)
})
};
Asynchronous Javascript allows you to execute operations without waiting for the processing thread to become free.异步 Javascript允许您在不等待处理线程空闲的情况下执行操作。
Imagine the data loads from your DB only after 3 seconds - you should "wait" to get the value from your DB before running the next line code.想象一下,数据仅在 3 秒后从您的数据库加载 - 在运行下一行代码之前,您应该“等待”从您的数据库获取值。 In your case you use myArr
"outside" without await -Or- promises -Or- callbacks ) - So the value is an empty array.在你的情况,你使用myArr
“外”没有的await -或- 承诺-或- 回调) -所以此值是一个空数组。
IMPORTANT: The idea of Asynchronous Javascript is a topic for a course (No way to cover this issue by StackOverflow Answer).重要提示:异步 Javascript 的想法是一门课程的主题(StackOverflow Answer 无法涵盖这个问题)。
length is: undefined长度为:未定义
function helloWorld() {
let items = db.collection("newspapers").find({}).toArray();
return (items);
};
const result = helloWorld();
console.log("length is: " + result.length); /* length is: undefined */
await
for the value from helloWorld()
function. await
来自helloWorld()
函数的值。
function helloWorld() {
let items = db.collection("newspapers").find({}).toArray();
return (items);
};
const result = await helloWorld();
console.log("length is: " + result.length); /* length is: 337 */
Promise chaining for example:以承诺链为例:
For this database:对于这个数据库:
[
{
"Newspaper": "The New York Times"
},
{
"Newspaper": "Washington Post"
}
]
const dbName = 'my_database';
await client.connect();
const db = client.db(dbName);
myArr = [];
db.collection("newspapers").find({}).toArray()
.then(
res => {
for (let i = 0; i < res.length; i++) {
myArr.push(res[i].Newspaper);
};
console.log(`The length is ${res.length} documents`) /* The length is 2 documents */
console.log(myArr); /* [ 'The New York Times', 'Washington Post' ] */
},
err => console.error(`Something went wrong: ${err}`),
);
try/catch Async/await example (Readable code pattern): try/catch Async/await 示例(可读代码模式):
const helloWorld = (async () => {
try {
let items = await db.collection("newspapers").find({}).limit(2).toArray();
return (items);
} catch (e) {
console.error(
`Unable to establish a collection: ${e}`,
)
}
})
const result = await helloWorld();
console.log("length is: " + result.length); /* length is: 2 */
More examples here: https://docs.mongodb.com/drivers/node/fundamentals/promises更多示例: https : //docs.mongodb.com/drivers/node/fundamentals/promises
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.