How to return express api response in a structured manner

Issue

i need help on this my express API endpoint. I need to get the users details response in a customise structured manner like

{
 "userId": "a38a8320-b750-41d1-a2d3-117dd286eeb5", //guid
 "firstName": "John", //string
 "lastName": "Doe",//string
 "accountId": "47cabec9-4e05-4744-b1c3-602a51dd86bc"//guid
}

My get endpoint is

router.get("/users", async (req, res) => {
  const users = await User.find();
  res.send(users)
});

The result I’m getting from postman below

[
    {
        "_id": "ba3136dd-94e8-48e6-89aa-1457c8bc540a",
        "firstName": "Segun",
        "lastName": "Ajibaye",
        "accountId": "8f061737-9500-4760-909d-9591c6c6c340",
        "__v": 0
    }
    
]         

                                 

Solution

You can use the map method to achieve that.

The callback you pass to the map method will be executed on every item inside the users array, and it will generate a new array with the result of each operation.

So your code could be like this:

router.get("/users", async (req, res) => {
  const users = await User.find();
  const mappedUsers = users.map(function (user) {
   return {
    userId: user._id,
    firstName: user.firstName,
    lastName: user.lastName,
    accountId: user.accountId
   }
  })
  res.send(mappedUsers)
});

Answered By – Eduardo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published