【问题标题】:How to get the collection name from called API如何从调用的 API 获取集合名称
【发布时间】:2020-02-26 11:33:36
【问题描述】:

我正在使用 mongoDB 开发节点 js 应用程序。当我调用该集合的 API 时,我需要帮助来获取集合名称。我想在中间件函数中使用它。

我从这里得到了调用 API 的方法。

const getmethod = req.method;

【问题讨论】:

    标签: node.js mongodb express mongoose mongodb-query


    【解决方案1】:

    您需要先创建Middleware,并获取集合列表并将其与请求绑定,如下所示。

    const mongoose = require('mongoose');
    const connection = mongoose.connect('mongodb://localhost:27017');
    
    const getmethod = req.method;
    
    app.use(function(req, res, next) {
        connection.on('open', function () {
            connection.db.listCollections().toArray(function (err, names) {
                if (err) {
                    console.log(err);
                    //Error in get collection
                    req.collectionName = '';
                    mongoose.connection.close();
                    next();
                } else {
                    console.log(names);
                    if(names.includes(getmethod)){
                        req.collectionName = getmethod;
                    }else{
                        //there is no collection exist for this method
                        req.collectionName = '';
                    }
                    mongoose.connection.close();
                    next();
                }
            });
        });
    });
    

    【讨论】:

    • 它将从数据库返回集合列表。但我每次调用 api 时只需要一个集合名称。对于 Example,我调用 api 来获取客户,在这种情况下,我想要该客户的集合名称的名称。
    • @sohilpatel 您可以检查您的方法是否存在于您的数据库中,如果是,那么您可以绑定集合名称,否则为空白,我编辑了我的答案,也许对您有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2016-01-19
    • 2020-08-24
    • 2016-09-08
    • 1970-01-01
    • 2017-09-06
    相关资源
    最近更新 更多