MongoDB与Express

时间:2017-03-20 17:44:02

标签: mongodb express

我正在尝试构建一个API,但是我遇到了障碍。 有许多非独特的"制作"在我的"样式"收藏,我想得到所有"制作"来自用户输入的类别(例如:Sedan)并且仅显示唯一的" Make"通过类别比较的对象。

注意:我没有使用' Mongoose',我使用的是原生驱动程序。

如何链接distinctfind方法(使用快递)?

使用以下代码:

  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)

1 个答案:

答案 0 :(得分:1)

试试这个

聚合操作MongoDB还提供了db.collection.distinct()

Documentation on distinct:

distinct

distinct command against a collection