I am using redis server to store key-value(username-socketID) pairs for a chat app in socket.io.
The problem i have faced is that the same username can login from different devices so will have different socketIDs. SO i have to associate an array of socketIDs against one username. I was trying to associate an array to the key but itseems to be taking only the first element of the array as a string. Below is my code
Setting the array to the key:
var socketIDs = [];
socketIDs.push(socket.id);
client.set(username, socketIDs, function (err) {
console.log("IN USERNAME EVENT" + username + ":" + socketIDs);
});
Getting the array from the key:
client.get(username, function (err, socketIDs) {
var i = socketIDs.indexOf(socket.id);
if (i != -1)
{
socketIDs.splice(i, 1);
}
client.set(username, socketIDs, function (err) {
console.log(username + " DISCONNECTED");
socket.disconnect();
});
});
When am trying to fetch the value associated with the username, i get just the socketID as a string and not the array format that i had originally added as.
Any fix for this? or what is the best way to approach my requirement of storing multiple values for a single key?
I would recommend using a list or a set. I would use a list unless you need duplication checks (if so then use a set). All the following examples are list based but you can find the equivalents for set here.
Adding a new socket ID
client.lpush(username, socket.id, function(err) {
console.log('Prepended new socket ID to list');
});
Getting all socket IDs for a user
client.lrange(username, 0, -1, function(err, socketIds) {
});
Removing a given socket ID
client.lrem(username, socketId, 0, function(err) {
});
(I've assumed you're using the node_redis lib).