title: Schema for chat application using mongodb
body: <p>I am trying to build a schema for chat application in <code>mongodb</code>. I have 2 types of user models - <code>Producer</code> and <code>Consumer</code>. Producer and Consumer can have conversations with each other. My ultimate goal is to fetch all the conversations for any producer and consumer and show them in a list, just like all the messaging apps (eg Facebook) do.</p>
  
  <p>Here is the <code>schema</code> I have come up with:</p>
  
  <pre><code>Producer: {
      _id: 123,
      'name': "Sam"
  }
  
  Consumer:{
      _id: 456,
      name: "Mark"
  }
  
  Conversation: {
      _id: 321,
      producerId: 123,
      consumerId: 456,
      lastMessageId: 1111,
      lastMessageDate: 7/7/2018
  }
  
  Message: {
      _id: 1111,
      conversationId: 321,
      body: 'Hi'
  }
  </code></pre>
  
  <p>Now I want to fetch say all the consersations of Sam. I want to show them in a list just like Facebook does, grouping them with 
  each Consumer and sorting according to time.
  I think I need to do following queries for this:</p>
  
  <p>1) Get all Conversations where producerId is <code>123</code> sorted by lastMessageDate.
    I can then show the list of all Conversations.</p>
  
  <p>2) If I want to know all the messages in a conversation, I make query on Message and get all messages where conversationId is <code>321</code></p>
  
  <p>Now, here for each new <code>message</code>, I also need to update the <code>conversation</code> with new messageId and date everytime. Is this the right way to proceed and is this optimal considering the number of queries involved. Is there a better way I can proceed with this?  Any help would be highly appreciated.</p>