How to handle a result from an hgetall() in nodejs (nowjs)?

wenbert picture wenbert · Aug 5, 2011 · Viewed 7.9k times · Source

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.

Answer

Jesper picture Jesper · Aug 6, 2011

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);
     });    
};