node.js - 在 REST API GET 请求中定义 MongoDB 集合

标签 node.js mongodb rest http express

我将 2 个单独的集合中的数据存储在同一个 MongoDB 数据库中。有没有办法在 HTTP GET 请求查询字符串中定义应该从哪个集合中检索数据。 我使用以下 JS 来处理查询:

const findDocuments = function(db, callback) {
const collection = db.collection('THIS should come from the query string');
collection.find(query).toArray(function(err, docs) {
  assert.equal(err, null);
  callback(docs);   
});
  };
};

应用程序是使用 express 在 Node.js 中设置的

dataRouter.route('/data')
.post(function(req, res){
    var query =req.query;
    //console.log(query);

    getResult(query, function(data){
        console.log('query done');
        //console.log(data);
        res.json(data);
    });
    module.exports = {
        query: query
    };
});

app.use('/api', dataRouter);

最佳答案

在您分享的示例中,您声明的是 POST 方法,而不是 GET。 无论如何,在 GET 方法中,您可以发送一个查询参数来标识您要使用的集合。 图片你发送一个名为集合的查询参数

http://myhost/data?collection=1

并且您可以使用以下方法提取该查询参数:

var numberCollection = req.query.collection;

关于node.js - 在 REST API GET 请求中定义 MongoDB 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064422/

相关文章:

node.js - 吉普 错误!堆栈错误: `C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe` failed with exit code: 1

angular - 在 Angular 4/Express 中访问响应状态代码

node.js - 在 Visual Studio 中发布 npm 模块文件夹

Node.js 后台任务

node.js - 为什么连接到 Node 中的 Mongo Db 需要这么长时间?

javascript - nodeJS、mongoDB、express、eJS - 关于内存缓存的意见

mongodb - 对每个请求进行反序列化?这不是不必要的数据库读取吗?

java - 如何将大输入流发送到 Spring REST 服务?

rest - 简单的 REST URL 方案

javascript - ExpressJS 将变量传递给 JavaScript