Node.js and Redis

Problem

I am trying to link up a redis database with a Node.js application I am building to be able to store comments about items. I'm using the node_redis library to handle the connection. When I attempt to retrieve the comments out of the database however only "[true]" is returned. For testing purposes I have stuffed everything into one method and I have hardcoded the values in, but I still receive "[true]".

exports.getComment = function (id){

var comments = new Array();

rc.hmset("hosts", "mjr", "1", "another", "23", "home", "1234");

comments.push(rc.hgetall("hosts", function (err, obj) {

    var comment = new Array();

    if(err){
        comment.push("Error");
    } else {
        comment.push(obj);
    }

    return comment;
}));

return comments;

}

Updated the code according to the tutorial and here is the result:

Retrieving the comment:

exports.getComment = function (id, callback){

  rc.hgetall(id, callback);

}

Adding the comment:

exports.addComment = function (id, area, content, author){

//add comment into the database
rc.hmset("comment", 
         "id", id, 
         "area", area, 
         "content", content,
         "author" , author,
         function(error, result) {
            if (error) res.send('Error: ' + error);
         });

//returns nothing

};

Code to render:

var a = [];
require('../lib/annotations').addComment("comment");
require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});
res.json(a);
Problem courtesy of: Chris Maness

Solution

The problem lays within the actual Redis-Node library when the call to addComment is made as it is below.

require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});

This call is missing an argument in the callback function. The first argument is the error report which should return null if everything is ok, the second is the actual data. So it should be structured like the call below.

require('../lib/annotations').getComment("comment", function(comment){
    a.push(err, comment)
});
Solution courtesy of: Chris Maness

Discussion

Node.js is asynchronous. Which means it asynchronously does the redis stuff, and then gets the result back in the callback function.

I suggest you read this tutorial and fully understand it before getting further: http://howtonode.org/node-redis-fun

Basically, this way won't work:

function getComments( id ) {
    var comments = redis.some( action );
    return comments;
}

But it has to be this way:

function getComments( id, callback ) {
    redis.some( action, callback );
}

This way, you use the API like this:

getComments( '1', function( results ) {
    // results are available!
} );
Discussion courtesy of: Florian Margaine

This recipe can be found in it's original form on Stack Over Flow.