I'm able to return the array of data using this:
router.get('/api/person', async (req, res) => {
const personData = await Person.find()
return res.json(personData)
})
But I'm not able to do so using this second method
router.get('/api/person', async (req, res) => {
const personData = await Person.find()
return res.json({personInfo:[{
id: personData._id,
name: personData.personName,
address: personData.personAddress
}]})
})
How should I return an array of data using the second method? Thanks
CodePudding user response:
Your question is not related to mongoose. What you are looking for is a javascript concept called map.
Your mongo query is returning the data that it has stored in it's database, there's nothing wrong in that. What you want to do after that is transform the incoming array into a different structure before sending it off.
With the help of map
we can iterate over the personData
array and create a new array with only the three elements that you require.
Your code should look like this (Definitely suggest you to read more about the map function so that you understand it well):
router.get("/api/person", async (req, res) => {
const personData = await Person.find();
const personInfo = personData.map((person) => {
return {
id: person._id,
name: person.personName,
address: person.personAddress,
};
});
return res.json({ personInfo });
});