アイテムに関するコメントを保存できるように、作成中の Node.js アプリケーションと redis データベースをリンクしようとしています。接続を処理するために node_redis ライブラリを使用しています。データベースからコメントを取得しようとすると、「[true]」のみが返されます。テスト目的で、すべてを 1 つのメソッドに詰め込み、値をハードコードしましたが、それでも「[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;
}
チュートリアルに従ってコードを更新した結果は次のとおりです。
コメントの取得:
exports.getComment = function (id, callback){
rc.hgetall(id, callback);
}
コメントの追加:
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
};
レンダリングするコード:
var a = [];
require('../lib/annotations').addComment("comment");
require('../lib/annotations').getComment("comment", function(comment){
a.push(comment)
});
res.json(a);