MongoDB Nested Query Returns Only Last Occuring Result MongoDB Nested Query Returns Only Last Occuring Result mongoose mongoose

MongoDB Nested Query Returns Only Last Occuring Result


To navigate the js async, I did some to and fro emitting with socket.io and it worked

on the server side

var query = records.find({$or:[{starter:data},{receiver:data}]},{});//check the records table for all persons the logged in user has spoken toquery.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;        }      var userlast = target+" "+lasttxt;                socket.emit('lastly', userlast);//Emit the username and last message for the client to emit back here    }})

On your client side, Pick up the emitted data

 socket.on('lastly', function(data){//Recieve the data and send right back                  socket.emit('lastly2', data);              });

Back on you server side, pick up the data sent back

socket.on('lastly2', function(data){//receive the username and last message to work withvar check = data;var space = check.indexOf(' ');var name = check.substr(0, space);var msg = check.substr(space+1);usersrec.find({username:name},{}).lean().exec(function (errx, docx){            if(errx) throw errx;            docx[0].message = msg;            socket.emit('usernames', docx);      });

Yeah its probably unorthodox, but at least it gets the job done. Im open to better suggestion tho