Is there a way to return an object from model.find({}) where the fields are mapped to their alias value. I need to convert _id to some other alias name. I am using mongoose node js

Is there a way to return an object from model.find({}) where the fields are mapped to their alias value. I need to convert _id to some other alias name. I am using mongoose node j

Hi,

You can use aggregate query with $project pipeline:

model.aggregate([
  {
    "$project": {
      "new_field": "$current_field"
    }
  }
])

Working Example

what i need is… I have my collection as
{ {
“_id”: ObjectId(“5a934e000102030405000000”), “'name” : “Arnold”
},
{
“_id”: ObjectId(“5a934e000102030405000001”), “'name” : “helen”
},
}
i need to query [model.find({filter}) from this collection to get the name as name and _id as userId

Hi,

You can do it like this:

model.aggregate([
  {
    "$project": {
      "name": 1,
      "userId": "$_id",
      "_id": 0
    }
  }
])

Working example