title: SocketIO Chat - Cannot read property of undefined
body: <p>I've set up a socketio chat. I'm trying to display old messages (from mongodb) when a user joins the channel.</p>
  
  <p>I'm able to join the chat for the first time, but if I load the page in a new tab I get the error "Uncaught TypeError: Cannot read property 'nick' of undefined - in the console.</p>
  
  <p>when I console.log(data.nick + data.msg), I get the data I'm looking for. I can't figure out what's causing this..</p>
  
  <p>Please help!</p>
  
  <p>Here's the relevant <strong>client side code:</strong></p>
  
  <pre><code>socket.on('load old messages', function(data) {
          for(var i=0; data.length; i++) {
               displayMsg(data[i]);
          }
  
        });
  
        function displayMsg(data) {
            $chat.append('&lt;span class="chatnick"&gt;&lt;b&gt;' + data.nick + ': &lt;/b&gt;&lt;/span&gt;&lt;span class="chatmsg"&gt;' + data.msg + "&lt;/span&gt;&lt;br/&gt;&lt;hr&gt;");
        }
  </code></pre>
  
  <p>Here's the relevant <strong>server side code:</strong></p>
  
  <pre><code>var query = Chat.find({});
  query.sort('-created').limit(8).exec(function(err, data) {
  if(err) throw err;
  socket.emit('load old messages', data);
  });
  </code></pre>
  
  <p>Here is my <strong>MongoDB code:</strong></p>
  
  <pre><code>mongoose.connect('mongodb://localhost:27017/chat-logs', function(err) {
  if(err) {
  console.log(err);
  } else {
  console.log("Connected to mongodb!");
  }
  });
  var chatSchema = mongoose.Schema({
  nick: String,
  msg: String,
  // channel: String,
  created: {type: Date, default: Date.now}
  });
  var Chat = mongoose.model('Message', chatSchema);
  </code></pre>