我将 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/