Reputation: 14355
In my node application i'm using redis DB to store the data.While getting the stored value using key i'm not getting the expected output.
var redis=require('redis');
var client = redis.createClient();
var pageContent={a: "a", b: "b", c: "c"};
//client.set('A',pageContent);//here i'm setting the value
client.get('A',function(err,res){
if(!err){
Object.keys(res).forEach(function(k){
console.log('key is '+k + ' value is '+res[k]);
});
}
else{
console.log('error');
}
});
Above code is not giving the stored value.While looping the result i'm getting the below error
TypeError: Object.keys called on non-object
So i have tried res.toString(); but i'm not getting the stored value instaed of that i'm getting only [object object];
Upvotes: 0
Views: 6162
Reputation: 39223
The issue is that you are trying to save an object with SET
. In redis, SET
and GET
only work with strings, so the reason you get [object Object]
back is that's the string which was saved in redis -- the string representation of your object.
You can either serialize your objects as e.g. JSON, using JSON.stringify
when saving, and JSON.parse
when reading, or you can save your objects as redis hashes, using HMSET
when saving, and HGETALL
(or HGET
/ HMGET
) when reading.
Edit: Note, though, that if you decide to use redis hashes, you cannot have "nested" objects -- i.e., you cannot store an object where one of the properties is an array or another object. That is,
{
a: 1,
b: 2
}
is okay, while
{
a: {
b: 2
}
}
is not. If you have such objects, you need another model (JSON with SET/GET works perfectly well in this case).
Upvotes: 5