2

I am using redis + nowjs. I would like to know how to go about handling a result from an hgetall()? When I try to display the "result" in the client side, I only get [object Object] (it is probably a string from the server-side js).

//Redis result is

redis> HSET cards:lightning-bolt name "Lightning Bolt"
(integer) 1
redis> HSET cards:lightning-bolt text "Blah blah blah"
(integer) 1
redis> HGETALL cards:lightning-bolt
1) "name"
2) "Lightning Bolt"
3) "text"
4) "Blah blah blah"
redis>

//In my server js

everyone.now.signalShowRedisCard = function(card_id) {
    var self = this;
    client.hgetall(("cards:%s" % card_id), function (err, res) {
        nowjs.getGroup(self.now.room).now.receiveShowRedisCard(res);
    });
}

//In my client js (the alert just outputs [object Object])

now.receiveShowRedisCard = function(card_data) {
    alert("redis card: "+card_data);
    try {
      console.log('card data: '+ card_data);
    } catch(e) {
      console.log("Firebug not installed.");
    }
}

Any ideas? Any reply is appreciated.

wenbert
  • 5,263
  • 8
  • 48
  • 77
  • Dont use `+` in `console.log` just use `console.log` or `console.dir` on an object directly. – Raynos Aug 06 '11 at 11:21
  • @Raynos thanks! I placed the plus sign for the 'card data: " - So that I can easily spot the specific log in Firebug since there are other lines of code logging in the console... Are there any issues I am not aware of when I use a + "plus"? I'm thinking that it converts the object into a string? If it does, then I probably should have used the + lol... Thanks again! – wenbert Aug 09 '11 at 02:58
  • 1
    your doing string concatenation. This means your implecitly calling `toString` on the object. Basically the console is better at logging data then the `toString` method. Use `console.log("card data: ");console.log(card_data);` instead – Raynos Aug 09 '11 at 09:10

2 Answers2

6

when using hgetall you get an array of objects back. Depending on the scenario it could be handled like this:

getItems = function(callback){   
    client.hgetall("myhash",function(err, res){
         var items = [];
         for (i in res) {
            items.push(JSON.parse(res[i]));
         }
     callback(items);
     });    
};
Jesper
  • 61
  • 2
4

From node_redis readme:

client.hgetall(hash)

The reply from an HGETALL command will be converted into a JavaScript Object by node_redis. That way you can interact with the responses using JavaScript syntax.

I don't know how exactly is nowjs handling passing JavaScript objects, but you can try to JSON.stringify the res returned from the hgetall on the server side and then see if you get JSON string on the client. If yes then just parse it back to JavaScript object in order to work with it on the client side.

yojimbo87
  • 65,684
  • 25
  • 123
  • 131