title: Mongoose Private Chat Message Model
body: <p>I'm trying to add private messaging between users into my data model.  I've been going back and forth between two possible ways of doing this.  </p>
  
  <p>1) Each user has an array of user_id, chat_id pairs which correspond to chats they are participating in. Chat model just stores chat_id and array of messages.</p>
  
  <p>2) Don't store chats with user at all and just have the Chat model store a pair of user_ids and array of messages.</p>
  
  <p>The issue with option (1) is whenever a user joins or starts a chat, I would need to look first through the array for the user to see if the user_id, chat_id pair already exists.  And then do a second find for the chat_id in Chat. If it doesn't exist, I would need to create the user_id, chat_id pair in two different places for both users who are participating.</p>
  
  <p>With option (2) I would search through the Chat model for the user_id1, user_id2 pair, and if I find it I'm done, if not I would create a new Chat record for that pair and done.</p>
  
  <p>Based on this option (2) does seem like the better way of handling this.  However, I'm running into issues figuring out how to model the "pair" of user ids in a way that they are easily searchable in the chat model.  i.e. how do I make sure I can find the chat record even if the user_ids are passed in the wrong order, i.e. user_id2, user_id1.  What would be the best way to model this in Mongoose?</p>
  
  <pre><code>var chatSchema = mongoose.Schema({
  
    messages: [{
          text: { 
            type: String,
            max: 2000
          },
          sender: { 
            type: mongoose.Schema.Types.ObjectId, 
            ref: 'User'
          }
        }],
    participant1: [{                
            type: mongoose.Schema.Types.ObjectId, 
            ref: 'User'
          }]
    participant2: [{                
            type: mongoose.Schema.Types.ObjectId, 
            ref: 'User'
          }]
  });
  </code></pre>
  
  <p>If it's something like above, how would I search for a participant pair?  Could I order the participant IDs in some way so that they are always participant1 &lt; participant2 for example, making search simpler?</p>