I am trying to query the database and get the first and last name of a user and use the object maping to dynamicaly add them to what should be returned to the frontend.
but after the everything i dont get the the firstname and lastname on the retuened values. find the code and what i expect below
const getMyCrushRequest = async (req, res) => {
// Check if user has sent any crush requests
const findCrush = await CrushRequest.findAll({
attributes: {exclude: ['requestFrom']},
where: {requestFrom: req.user.id}
});
// If user has not sent any crush requests
if(!findCrush || findCrush.length == 0){
return res.status(StatusCodes.OK).send({
success: false,
message: 'you have not sent any crush requests'
});
}
// Map the crush requests to include the first and last name of the recipient
const requests = await Promise.all(findCrush.map(async (crush) => {
const nameQuery = await User.findOne({
attributes: ["firstname", "lastname"],
where: {id: crush.requestTo}
});
// Add the user details to the crush request object
crush.firstname = nameQuery.firstname;
crush.lastname = nameQuery.lastname;
return crush;
}));
// console.log (JSON.stringify(requests))
// Return the mapped crush requests
return res.status(StatusCodes.OK).json({
success: true,
message: 'Crush request retrieved successfully',
requests: requests
});
}
Below is the response i get
{
"success": true,
"message": "Crush request retrieved successfully",
"requests": [
{
"id": 2,
"requestTo": "d8b60bcb-c1f4-41c9-8f0b-4f3baf734b06",
"requestStatus": "pending",
"createdAt": "2022-12-12T16:45:02.000Z",
"updatedAt": "2022-12-12T16:45:02.000Z"
},
{
"id": 3,
"requestTo": "f6516bd8-2577-468c-9779-3f271b6a03db",
"requestStatus": "pending",
"createdAt": "2022-12-12T17:06:12.000Z",
"updatedAt": "2022-12-12T17:06:12.000Z"
}
]
}
Here was what i espected
{
"success": true,
"message": "Crush request retrieved successfully",
"requests": [
{
"id": 2,
"requestTo": "d8b60bcb-c1f4-41c9-8f0b-4f3baf734b06",
"firstname": "Somename",
"lastname": "someorthername",
"requestStatus": "pending",
"createdAt": "2022-12-12T16:45:02.000Z",
"updatedAt": "2022-12-12T16:45:02.000Z"
},
{
"id": 3,
"requestTo": "f6516bd8-2577-468c-9779-3f271b6a03db",
"firstname": "Somename",
"lastname": "someorthername",
"requestStatus": "pending",
"createdAt": "2022-12-12T17:06:12.000Z",
"updatedAt": "2022-12-12T17:06:12.000Z"
}
]
}