OmarElgabry/chat.io

Uncaught TypeError: Cannot create property 'username' on string '59101c3aa72c3e279bb4aeb1'

BjoernEnd opened this issue · 3 comments

Hello, excuse for my bad one in English. I use a translator. Today I have ascertained something strange. I have thought, it is due to the fact that I have altered the chat. After some tests I have the original try tested. There this mistake also appears. I have tested it with a lot of devices and browser.

If a user is already in a chat space and a new user announces himself who enters then this chat space, this sees the users does not list.

the Google-Chrome-Console shows the following mistake:

Uncaught TypeError: Cannot create property 'username' on string '59101c3aa72c3e279bb4aeb1'

Is this problem known? I ask for help. I find of the chat first-class. So I would adapt this with pleasure on my needs and extend!

Many greetings

Björn End

The problem seems to be originating from models/room.js in the getUsers function. The first loop tries to create an array of userId. For some reason, the first item in the users array got skipped in the second for loop.

I managed to fix the bug by ignoring the order of the users assigned to the users array, the reason is mainly that User.findById is an asynchronous call to mongoDB and if one of the previous user was not returned before the last one does, the callback is returned.

var getUsers = function(room, socket, callback){

	var users = [], vis = {}, curr = 0, count = 0;
	var userId = socket.request.session.passport.user;

	// Loop on room's connections, Then:
	room.connections.forEach(function(conn){
			// 1. Count the number of connections of the current user(using one or more sockets) to the passed room.
			if(conn.userId === userId){
				curr++;
			}
			// 2. Create an array(i.e. users) contains unique users' ids
			if(!vis[conn.userId]){
				User.findById(conn.userId, function(err, user){
					user.password = null;
					users.push(user);
					if (count === room.connections.length){
						return callback(null, users, curr);
					}
				});
			}
			vis[conn.userId] = true;
			count++;
	});
}

I updated the code as investigated by @rayonx . Hope this will solve the problem.