'Searching for all properties of a document using aggrigation and project with change in date fomat in mongoose

My database model looks like

{
  email: { type: String, required: true },
  name: { type: String, required: true },
  projectId: { type: String, required: true },
  createdAt: { type: Date, required: false },
  updatedAt: { type: Date, required: false },
};

createdAt is of format 2021-10-07T11:16:44.988Z and I wants at the time of fetching data from database date format should be 2022-02-25. so I made quiry to database as bellow:-

const { id } = req.params;
const participantList = await ParticipantModel.aggregate([
  { $match: { projectId: id } },
  { $limit: limitInt },
  { $skip: skipInt },
  {
    $project: {
      Date: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
    },
  },
]);

I got result as below:-

  { _id: 6218e52f43ec044180e69b84, Date: '2022-02-25' },
  { _id: 6218e5f543ec044180e69b97, Date: '2022-02-25' },

]

Expected result


[
  { _id: 6218e52f43ec044180e69b84,email:'[email protected]', name:'xyz',projectId:"01A", Date: '2022-02-25',updatedAt: 2022-02-25T14:18:23.708Z},
  { _id: 6218e5f543ec044180e69b97, email:'[email protected]', name:'abc',projectId:"01B",Date: '2022-02-25' , updatedAt: 2022-02-25T14:21:41.313Z,},
]
  

How to solve this? Thank you for your help.



Solution 1:[1]

In $project guide of mongodb docs, set value to 1 each field if you want to show or 0 to hidden:

const { id } = req.params;
const participantList = await ParticipantModel.aggregate([
          {$match:{projectId:id},},{$limit:limitInt},{$skip:skipInt},{$project:{
            Date: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
            email: 1, name: 1, projectId: 1, updatedAt: 1
          }}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VMT