猫鼬 $ 项目

Mongoose $ project

使用 Mongoose 4.0.x,我需要执行以下(有效)MongoDB 查询:

db.bookings.find(
  {
    user: ObjectId("10"), // I replaced the real ID
    'flights.busy.from': {$gte: ISODate("2015-04-01T00:00:00Z")},
    'flights.busy.to': {$lte: ISODate("2015-04-01T23:59:00Z")}
  },
  {
    'flights.$': 1 // This is what I don't know to replicate
  }
).pretty()

Mongoose find operator does not accept a projection operator, like the MongoDB find 一个。

如何在 Mongoose 中复制上述查询?一旦返回查询就过滤数组是我想避免的解决方案。

您想查看 Model.find 的文档,而不是 Query.find。第二个参数可用于字段选择:

MyModel.find(
  {
    user: ObjectId("10"), // I replaced the real ID
    'flights.busy.from': {$gte: ISODate("2015-04-01T00:00:00Z")},
    'flights.busy.to': {$lte: ISODate("2015-04-01T23:59:00Z")}
  },
  'flights.$'
).exec(function(err, docs) {...});