我正在使用mongoDB开发Node js应用程序。调用该集合的API时需要获取集合名称的帮助。我想在中间件函数中使用它。
我从中得到了称为API的方法。
const getmethod = req.method;
答案 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();
}
});
});
});