I have been trying to create a JSON object with the data that I pull from MongoDB database.
Last line res.status(200).json(userData) seems to return a response before the data processing is over, so I get an empty object without processed data as a response. Any ideas on how to solve this problem?
// chats are defined before, but excluded here to make a code easier to read
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 shows that there is a data coming from the database:
{ imageUrl: 'www.test.de', firstName: 'Fender', lastName: 'Fen' }
{ imageUrl: 'www.test.de', firstName: 'Baveler', lastName: 'Bav' }
Thank you for your time