Want to store in Redis via Node.js

XMen picture XMen · Jun 1, 2011 · Viewed 10.4k times · Source

I want to store a hash/JSON data of users in Redis and want to add the user in users hash the user data like this.

For example, users = {};

When user rahul logs in then users will become.

users = {
    rahul: {
        username: 'rahul',          
    }
}

And when user namita login then

users = {
    rahul: {
        username: 'rahul',

    },
    namita: {
        username: 'namita',

    }
}

What will the code be to do this in Redis?

How will I initialise the key users and add rahul to it?

Out of this set, hset, etc., which function do I need to use?

And how will I retrieve the data of users['rahul'] via Redis?

Answer

yojimbo87 picture yojimbo87 · Jun 1, 2011

Probably the most optimal solution to store single hash/json would be to use hashes commands. I also had this "dilemma" and there are several questions regarding data structure containing users with JSON-like objects in Redis.

EDIT

Use node_redis module. It's actively maintained by a pro a probably the most used node.js driver for Redis. First you should use SADD command to add your new JSON object name into the set in order to track which items "users" contain. Then use HMSET to store "user:rahul" object key-value hashes. Example:

// add first user
client.sadd("users", "user:rahul");
client.hmset("user:rahul", "username", "rahul", "foo", "bar");

// add second user
client.sadd("users", "user:namita");
client.hmset("user:namita", "username", "namita", "foo", "baz");

You can now access your users by various types of redis hash command depending if you want to retrieve only certain hash values or the entire single user object. To get all of the users you can use SMEMBERS command for example. Try to look at the node_redis readme and examples where you should find more information about its API.