I am using Node.js and a Redis Database . I am new to Redis .
I am using the https://github.com/mranney/node_redis driver for node.
Initialization code -
var redis = require("redis"),
client = redis.createClient();
I tried setting up some key value pairs -
client.hset("users:123" ,"name", "Jack");
I wish to know I can get the name parameter from Redis via Node .
I tried
var name = client.hget("users:123", "name"); //returns 'true'
but it just returns 'true' as the output. I want the value ( i.e - Jack ) What is the statement I need to use ?
This is how you should do it:
client.hset("users:123", "name", "Jack");
// returns the complete hash
client.hgetall("users:123", function (err, obj) {
console.dir(obj);
});
// OR
// just returns the name of the hash
client.hget("users:123", "name", function (err, obj) {
console.dir(obj);
});
Also make sure you understand the concept of callbacks and closures in javascript and then the asynchronous nature of node.js. As you can see you pass a function (callback or closure) function to hget. This function gets called as soon as the redis client has retrieved the result from the server. The first argument will be an error object if there is any, otherwise the first argument will be null. THe second argument will hold the results.
I found the answer -
A callback function is needed for getting the values .
client.hget("users:123", "name", function (err, reply) {
console.log(reply.toString());
});