我正在使用mongoDB开发一个node js应用程序。当我调用该集合的API时,我需要帮助来获取集合名称。我想在中间件函数中使用它。
我从这里得到了调用API的方法。
const getmethod = req.method;
发布于 2019-10-31 06:26:18
您需要先创建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();
}
});
});
});
https://stackoverflow.com/questions/58637727
复制相似问题