I am working on a chat application. I have chat history in chats table. Now I want to see the latest message of each chat by using the sender email. So, I am getting the chat id by using distinct query as shown below
var userChat = [];
Chat.distinct("chatId", {"senderEmail" : req.params.Email}, function(err, result){
if( result){
console.log(result);
for(var i = 0; i < result.length; i++){
Chat.find({ chatId: result[i] }).sort('-_id').limit(1).exec(function(error, result)
{
if(result){
console.log(" IN FOR LOOP ");
userChat.push(result);
}
});
}
console.log("USER CHAT ARRAY : ", userChat);
}
});
After running the distinct query I got 4 chat ids [ '114143', '130997', '457884', '479310' ]
Now the problem is that whenever I call push then it is not pushing result array from find query into the userChat array. Also I have noticed that the console of USER CHAT ARRAY is called BEFORE for loop console. Following is the screenshot of the console
