如何从调用的API获取集合名称

时间:2019-10-31 06:13:26

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

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

我从中得到了称为API的方法。

const getmethod = req.method;

1 个答案:

答案 0 :(得分:0)

您需要首先创建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();
            }
        });
    });
});