gpt4 book ai didi

javascript - 如何将 mongoose 集合的返回值存储到 JavaScript 数组中?

转载 作者:行者123 更新时间:2023-12-03 02:10:31 25 4
gpt4 key购买 nike

在我的 JavaScript 程序中,我想获取从 MongoDB 获取的“Booking”集合,然后将返回值存储到 JavaScript 变量中。

router.get('/dashboard', function(req, res){
//hardcode some value for testing, the program can pass this value.
var booking = [{id: 1, name:"AAA"}, {id: 2, name:"BBB"}, {id: 3, name:"CCC"}];

Booking.collection.find().toArray(function(err, docs) {
console.log(docs);
console.log("S-------------------------------------------------");
// assign the returned value from collection to "booking" variable
booking = docs; // Booking variable can store the value.
console.log(booking); //can print the value here
console.log("E-------------------------------------------------");
});

// After execution of above statement, "booking" variable does not contain any value
// (because I cannot get the value after running the last code.)
// Why?? How can I resolve it?

// The "booking" variable does not contain value after execution of below code.
res.render('dashboard', {booking:booking});
});

我可以成功获取返回值,但我不知道如何将此值存储在本地 JavaScript 变量中以进行进一步操作。

有人建议如何解决这个问题吗?谢谢。

最佳答案

好吧,这里的问题是 Mongoose 操作是异步的。所以你应该在回调中管理预订数据

`

Booking.collection.find().toArray(function(err, docs) {
if(!err){
res.render('dashboard', {booking:docs});
}
});

`

我还建议您在单独的模块中管理所有数据库交互(获取、添加、删除...),这是一个很好的做法。它可能是一个helper文件夹。

Helpers are 'general' helper objects (not feature specific) that execute 'static' functions that are useful throughout the entire application. For example, a function that manages string or date parameters, a function that parses the response of an ajax call, a function that manages proper cleanup of view objects, etc... https://www.quora.com/What-is-the-best-folder-structure-practice-for-Javascript-Backbone-related-to-delegate-helper-functions

然后使用回调函数或 promises 管理他们的响应.

关于javascript - 如何将 mongoose 集合的返回值存储到 JavaScript 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594424/

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