title: How to generate a room id and force two users to join that room?
body: <p>Im building a chat application in node.js , socket.io and mongoose. My goal is to build a one on one chat, it is similar like facebook web chat. So basically whenever I click on a user it will go to that user url and possibly chat with him/her</p>
  
  <p>But the problem, that I'm facing is that I could only emit the message to the targeted user, but not to myself.</p>
  
  <p>Here's the current code</p>
  
  <p>Serverside</p>
  
  <pre><code>socket.on('chatTo', function(data){
        User.findOne({ username: data.destinationUsername, socketId: { '$ne': null}}, function(err, foundUser) {
          if (foundUser) {
            io.to(foundUser.socketId).emit('incomingChat', { sender: user.username, message: data.message });
  
          } else {
            io.to(socket.id).emit('deliverError', { error: foundUser + ' is not online' });
  
          }
        });
      });
  </code></pre>
  
  <p>Clientside</p>
  
  <pre><code>$(function() {
  
    var socket = io();
  
  
    function chatTo(message, destinationUsername) {
      socket.emit('chatTo', { message: message, destinationUsername });
    }
  
  
    $('#sendMessage').submit(function(){
      var input = $('#message').val();
      var username = $('#username').val();
      chatTo(input, username);
      $('#message').val('');
      return false;
    });
  
  
    socket.on('incomingChat', function(data) {
      var html = data; // Messages to append to media-list
  
      $('.media-list').append(html);
    });
  });
  </code></pre>
  
  <p>So what is happening here is that, on the clientside, User A clicks form submit , to submit the message, it will invoke <code>chatTo</code> function and emit the data. Just want to let you guys know, <code>input</code> and <code>username</code> are from html page. It would look something like this</p>
  
  <pre><code>input = "Hello";
  
  username = "jackmoscovi" // user's username
  </code></pre>
  
  <p>then it will emit both of these data back to server, which is <code>socket.on('chatTo')</code> is listening to. After some MongoDB operation, if found the user then emit to that specific socket.</p>
  
  <p>The result will be</p>
  
  <p><a href="https://i.stack.imgur.com/8iSwH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8iSwH.png" alt="enter image description here"></a></p>
  
  <p>The message that was emitted by batman only shows up on joker's page but not on Batman's page. I know that because I specifically emit to that socket. The real question is How do I force both of these user to be in a unique room? Should I create a new <code>Room mongoose model</code>? and then call <code>socket.join('uniqueRoom')</code>?</p>
  
  <p>and then simply <code>io.to('uniqueRoom').emit("Message?");</code></p>
  
  <p>How would I implement this room mechanism?</p>
  
  <p>I have been struggling for 2 days already, please someone end this misery :(</p>