Exclude specific fields in all nested document in mongoose query

Viewed 33

I have a ride Collection with trips as a field, trips is a map where the keys are different years. I want to query the collection but exclude the passengers field in each trip

const ride = new Schema(
    {
        boat_operator: {
            type: Schema.Types.ObjectId,
            required: true,
            ref: 'User'
        },
        trips: {
            type: Map,
            of: {
                passengers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
                available_seats: { type: Number, required: true }
            },
            default: new Map()
        }  
    }
    )

I tried this

const rides = await Ride.find({ status: 'waiting' }).select("-trips.*.passengers")

I tried to select all the items in value then remove the corresponding passengers field in each

It had no effect

this is what the response looks like

[
    {
        "_id": "632a1669279c86f4ab3a4bf5",
        "boat_operator": "6328c434a98212a7f57c4edc",
        "trips": {
            "2019": {
                "passengers": [],
                "available_seats": 5,
                "_id": "632a1669279c86f4ab3a4bfe"
            },
            "2020": {
                "passengers": [],
                "available_seats": 5,
                "_id": "632a1669279c86f4ab3a4bfc"
            },
            "2021": {
                "passengers": [],
                "available_seats": 5,
                "_id": "632a1669279c86f4ab3a4bfa"
            },
            "2022": {
                "passengers": [],
                "available_seats": 5,
                "_id": "632a1669279c86f4ab3a4bf8"
            }
        }
    }
]

I want to exclude the passengers field in the returned document

1 Answers

This would solve it

const rides = await Ride.aggregate([
  { "$match": { "status": "waiting" } },
  { $project: { "trips": { $objectToArray: '$trips' } } },
  { $project: { 'trips.v.passengers': 0 } },
  { $project: { "trips": { $arrayToObject: '$trips' } } }
]);

Here's the returned document

{
  "_id": "632a1669279c86f4ab3a4bf5",
  "trips": {
    "2019": {
      "available_seats": 5,
      "_id": "632a1669279c86f4ab3a4bfe"
    },
    "2020": {
      "available_seats": 5,
      "_id": "632a1669279c86f4ab3a4bfc"
    },
    "2021": {
      "available_seats": 5,
      "_id": "632a1669279c86f4ab3a4bfa"
    },
    "2022": {
      "available_seats": 5,
      "_id": "632a1669279c86f4ab3a4bf8"
    }
  }
}
Related