I've been working on creating a JSON object using data pulled from a MongoDB database.
The issue I'm facing is that the last line res.status(200).json(userData) seems to send a response before the data processing is complete, resulting in an empty object being returned without any processed data. Any suggestions on how to resolve this issue?
// The 'chats' variable is defined elsewhere
let userData = {};
chats.forEach(function(chat){
let chatId = chat.id;
let userIds = chat['userIds'];
UserAccountingData.find({userId: {$in : userIds}}, function(err, userAccountingData){
if(err){
console.log(err);
res.status(404).json('User data not found.');
return;
} else {
userAccountingData.forEach(function(data){
console.log({
imageUrl: data.imageUrl,
firstName: data.firstName,
lastName: data.lastName
});
userData[data.userId] = {
imageUrl: data.imageUrl,
firstName: data.firstName,
lastName: data.lastName
};
});
}
});
});
res.status(200).json(userData);
Console.log confirms that data is being retrieved from the database:
{ imageUrl: 'www.test.de', firstName: 'Fender', lastName: 'Fen' }
{ imageUrl: 'www.test.de', firstName: 'Baveler', lastName: 'Bav' }
Thank you for your assistance.