javascript - Can't merge results of query to create instant messaging inbox that shows latest messages -


i working on thread/conversation-based instant messaging feature (much facebook, hangouts, etc.). trying api serve list of conversations authenticated user participant in, along recent message in each of conversations.

i have been stuck on few days now, , have tried quite few things. haven't had luck aggregates. if made messages subdocument of conversations, have read has said avoid nesting boundless arrays that. curious if should consider schema redesign, first want see if there query can me need be.

this schema setup:

conversation.js:

const mongoose = require('mongoose'),       schema = mongoose.schema;  // schema defines how chat messages stored in mongodb const conversationschema = new schema({   participants: [{ type: schema.types.objectid, ref: 'user'}], });  module.exports = mongoose.model('conversation', conversationschema); 

message.js:

const mongoose = require('mongoose'),       schema = mongoose.schema;  const messageschema = new schema({   conversationid: {     type: schema.types.objectid,     required: true   },   body: {     type: string,     required: true   },   author: {     type: schema.types.objectid,     ref: 'user'   } }, {   timestamps: true // saves createdat , updatedat dates. createdat our timestamp. });  module.exports = mongoose.model('message', messageschema); 

here query has gotten me closest desired result far:

// return 1 message each conversation display snippet   conversation.find({ participants: req.user._id })    .select('_id')    .exec(function(err, conversations) {      if (err) {        res.send({ error: err });        return next(err);      }       let fullconversations = [];      conversations.foreach(function(conversation) {        message.find({ 'conversationid': conversation._id })         .sort('-createdat')         .limit(1)         .exec(function(err, message) {           fullconversations.concat(message);           console.log(message);        });      });      res.status(200).json({ conversations: fullconversations }); }); } 

the right information logging in console. have tried pushing , concatenating fullconversations array, ends being empty in response. not sure running separate query each individual conversation foreach. doesn't seem efficient me, i'm struggling find way works. or advice appreciated. thank you!

i going guess you're functions updating fullconversations array being run asynchronously return fullconversations array before functions add data it.

let fullconversations = []; var notcompleted = conversations.length; conversations.foreach(function(conversation) {   message.find({ 'conversationid': conversation._id })    .sort('-createdat')    .limit(1)    .exec(function(err, message) {      fullconversations.push(message);      notcompleted--;      console.log(message);   }); });  while (notcompleted > 0) {     // wait }  res.status(200).json({ conversations: fullconversations }); 

Comments