router.get('/pictures', (req, res, next) => {
Picture.find()
.then(handle404)
.then(pictures => {
return pictures.map(picture => picture.toObject())
})
.then(pictures => {
pictures.map(picture => {
User.findById(picture.owner)
.then(owner => {
picture.ownerName = owner.username
console.log(pictures, "my picture with owner")
return pictures
})
.then(pictures => res.status(200).json({ pictures: pictures }))
})
})
.catch(next)
})
})
In order of operations: I need to find all pictures, then loop over the pictures array and find the username of the owner, then add a key in the pictures array with the owner username, then send the response with the new array of pictures that includes the owner's username
I want to return the pictures array with the found owner names.. but I am having an issue with the response being sent before the owner name is being set and Im not sure how to get the response to wait. If there is just one owner name its fine, but more than one and I get an error -
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I think this means my response is being sent before my query is completed.