【问题标题】:Render multiple MongoDB collections in same path (Express)在同一路径中渲染多个 MongoDB 集合 (Express)
【发布时间】:2020-11-03 02:16:31
【问题描述】:

我的 Express 应用程序中有 get 方法,它从我的 MongoDB 中呈现一个名为“成员”的集合。这有效,我可以在 url “/agileApp” 上读取结果。但是,我想将另一个集合呈现到同一个 URL 中——一个名为“Tasks”的集合。这可能吗?这是我当前的代码:

expressApp.get('/agileApp', function(request, response) {
    MongoClient.connect(url,
        {useUnifiedTopology: true},
        function(error, db) {
            if (error) {
                throw error;
            }
            let databaseobject = db.db(dbName);
                databaseobject.collection("Members").find().toArray(function (err, result) {
                    if (err) throw err;
                    response.render('agileApp', {
                        result: result,
                    });
                    db.close();
                });
        });
});

【问题讨论】:

    标签: javascript mongodb express vue.js


    【解决方案1】:

    只需要一个请求参数来决定要呈现哪个集合,并根据该值呈现该集合。

    expressApp.get('/agileApp', function(request, response) {
    // take the collection to render as request parameter (this is form parameter, json also can be used)
    let collectionToRender = request.params.collectionToRender
    MongoClient.connect(url,
        {useUnifiedTopology: true},
        function(error, db) {
            if (error) {
                throw error;
            }
            let databaseobject = db.db(dbName);
                // here it will query the mongodb for the collection which has been provided in the request
                // if user enters Tasks then Tasks collection will be rendered
                databaseobject.collection(collectionToRender).find().toArray(function (err, result) {
                    if (err) throw err;
                    response.render('agileApp', {
                        result: result,
                    });
                    db.close();
                });
        });
      });
    

    【讨论】:

    • 所以用户并没有真正输入任何东西。我只需要在输入 /agileApp 时呈现两个集合。
    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2013-08-20
    • 2016-06-10
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多