aravindnc / mongoose-aggregate-paginate-v2

A cursor based custom aggregate pagination library for Mongoose with customizable labels.
MIT License
131 stars 23 forks source link

Rename _id fields to id for the result #30

Closed awesomelike closed 3 years ago

awesomelike commented 3 years ago

In my schema, I have a mongoose virtual field id which is equal to _id. Generally, it works fine.

However, when I use this library, this virtual field is not working (it is showing _id, but the id virtual field disappeared). I have tried $project stage in the aggregation pipeline:

{
        $project: {
          id: '$user._id',
          _id: 0
        }
}

But it is removing all other fields from the response, (only id is there). It is very annoying to explicitly list all the necessary fields with field1: 1, field2: 1

What is the proper way to rename _id field to id while using this library? In other words, how to keep virtuals fields?

dennisMeeQ commented 3 years ago

You cannot remove and add a field in the same aggregate stage to my knowledge. I would use these two stages:

[
  ...  
  { $addFields: { id: "$_id" } },
  { $project: { _id: 0 } },
  ...
]

Have not tested with this library, though.

awesomelike commented 3 years ago

Yes, this works