MongoDB和表达互动的新手。我正在尝试基于URL参数查询数据库,本质上我想获取URL参数然后将它们添加到对象(如果它们存在时要查询数据库时使用)。我设置了我的快速路径并理解find()方法接受一个对象,当我像下面那样对键值对进行硬编码时,我得到了正确的数据,但是当我设置一个名为filter的对象时,它具有相同的键值对硬编码的示例和取消注释过滤器和注释状态和类型然后将它传递给find方法我得到一个空数组。究其原因是什么,最好的方法是什么?
app.get('/query', function (req, res) {
var filter = {
state: "florida",
type: "red"
}
db.collection('tickets').find({
//filter
state:"florida",
type:"red"
})
.toArray(function (err, documents) {
// Here is where we decide what to do with the query results
if (err)
throw err
res.send(documents)
})
});
答案 0 :(得分:2)
find
方法接受查询对象作为第一个参数,查询对象本身就是您的filter
对象。因此,你应该这样做:
db.collection('tickets').find(filter)
.toArray(function (err, documents) {
// Here is where we decide what to do with the query results
if (err)
throw err
res.send(documents)
})