Okay, I have this code containing a nested query inside a for loop
var query = records.find({$or:[{starter:data},{receiver:data}]},{});//check the records table for all persons the logged in user has spoken to
query.sort('-createDate').exec(function (err, docs){
if(err) throw err;
for(var i=docs.length-1; i>= 0; i--)
{
var starter = docs[i].starter;
var receiver = docs[i].receiver;
var lasttxt = docs[i].lastMessage;
if (starter == socket.usernames){
var target = receiver;
}else
{
var target = starter;
}
usersrec.find({username:target},{}).lean().exec(function (errx, docx){
if(errx) throw errx;
docx[0].message = lasttxt;
socket.emit('usernames', docx);
});
}
})
Its meant to get the last message of each person the currently logged in user has spoken to and store in the lasttxt
variable.
Problem is it only gets the last message of the last user in the database
It then then assigns this last message to everyone as their own last msg.
This doesn't affect the database's record. just the client side What am i missing?