MongoDB使用Express进行区分和查找
我正在尝试构建一个API,但是我遇到了一个障碍。 在我的“styles”集合中有许多非唯一的“Make”,我希望从用户输入(例如:Sedan)中获得所有类别的“Make”,并仅显示通过类别比较的唯一“Make”对象 注意:我没有使用“Mongoose”,我使用的是本机驱动程序 如何链接MongoDB使用Express进行区分和查找,mongodb,express,Mongodb,Express,我正在尝试构建一个API,但是我遇到了一个障碍。 在我的“styles”集合中有许多非唯一的“Make”,我希望从用户输入(例如:Sedan)中获得所有类别的“Make”,并仅显示通过类别比较的唯一“Make”对象 注意:我没有使用“Mongoose”,我使用的是本机驱动程序 如何链接distinct和find方法(使用express) 使用以下代码: router.get('/makes/:category', function(req, res) { var collection =
distinct
和find
方法(使用express)
使用以下代码:
router.get('/makes/:category', function(req, res) {
var collection = db.get().collection('styles')
console.log(req.params.category)
collection.distinct('make').find({'categories.vehicleStyle': req.params.category}, {'make': 1}).toArray(function(err, docs) {
res.send(docs)
})
})
预期产出:
[
{
"Make": "Acura",
"Make: "BMW"
}
]
我得到以下错误:
TypeError: collection.distinct(...).find is not a function
at C:\path\server\routes\api.js:67:31
at Layer.handle [as handle_request] (C:\path\node_modules\express\lib\router\layer.js:95:5)
at next (C:\path\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\path\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\path\node_modules\express\lib\router\layer.js:95:5)
at C:\path\node_modules\express\lib\router\index.js:281:22
at param (C:\path\node_modules\express\lib\router\index.js:354:14)
at param (C:\path\node_modules\express\lib\router\index.js:365:14)
at Function.process_params (C:\path\node_modules\express\lib\router\index.js:410:3)
at next (C:\path\node_modules\express\lib\router\index.js:275:10)
试试这个
聚合操作MongoDB还提供db.collection.distinct()
您可以尝试
collection.distinct('make',{'categories.vehicleStyle':req.params.category}).toArray(函数(err,docs){res.send(docs)})
这很有效!非常感谢!!