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

时间:2018-04-01 03:08:04

标签: javascript mongodb mongoose

在我的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变量中以便进一步操作。

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

1 个答案:

答案 0 :(得分:1)

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

`

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

`

我还建议您在一个单独的模块中管理所有数据库交互(获取,添加,删除...)。它可以是帮助文件夹。

  

助手是执行“静态”功能的“通用”辅助对象(不是特定功能),这些功能在整个应用程序中都很有用。例如,管理字符串或日期参数的函数,解析ajax调用响应的函数,管理视图对象正确清理的函数等等...... https://www.quora.com/What-is-the-best-folder-structure-practice-for-Javascript-Backbone-related-to-delegate-helper-functions

然后使用回调函数或promises管理他们的回复。