0

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

1 Answer 1

1

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 });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.