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');
}
});
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
So i have tried res.toString(); but i'm not getting the stored value instaed of that i'm getting only [object object];
问题是您正在尝试使用 保存对象SET。在 Redis 中,SET只能GET使用字符串,因此返回的原因[object Object]是保存在 Redis 中的字符串——对象的字符串表示形式。
您可以将对象序列化为 JSON,JSON.stringify在保存和JSON.parse读取时使用,也可以将对象保存为 Redis 哈希,HMSET在保存时使用,以及HGETALL(或HGET/ HMGET)在读取时使用。
编辑:但请注意,如果您决定使用 Redis 哈希,则不能拥有“嵌套”对象——即,您不能存储其中一个属性是数组或另一个对象的对象。那是,
{
a: 1,
b: 2
}
Run Code Online (Sandbox Code Playgroud)
没关系,同时
{
a: {
b: 2
}
}
Run Code Online (Sandbox Code Playgroud)
不是。如果您有这样的对象,则需要另一个模型(带有 SET/GET 的 JSON 在这种情况下工作得很好)。
| 归档时间: |
|
| 查看次数: |
5960 次 |
| 最近记录: |