2012-10-05 52 views
1

基本上我試圖設置一個給定的值的對象,但我不能讓它工作,即使它似乎成功。這是我的JavaScript對象;Redis:保存與列表的Javascript對象

function student(){ 
    var newStudent = {}; 
    newStudent.lessons = [1,3,4]; 

    return newStudent; 
} 

,當我想獲得學生列表我失敗,因爲打印的console.log後來「未定義」但對象是不爲空。我的代碼插入到redis;

var student = Students.student(); 
//Object is not null I checked it 
client.set("studentKey1", student, redis.print); 
    client.get("studentKey1", function(err, reply){ 
     console.log(reply.lessons); 
    }); 

兩個問題;

首先,我該如何正確地做,或者是Redis中不支持JavaScript的列表結構。其次,如果我想獲得帶有studentKey1的項目並將項目插入列表的後面,我該如何完成該項目(我如何利用RPUSH)?

回答

5

如果您只想保存整個Javascript對象,則需要先將其轉換爲字符串,因爲Redis只接受字符串值。

client.set('studentKey1', JSON.stringify(student), redis.print); 

在未來,如果你的student對象具有以下功能:請記住,這些不會被序列化,並存儲在緩存中。從緩存中獲取對象後,您需要重新水化對象。

client.get('studentKey1', function (err, results) { 
    if (err) { 
     return console.log(err); 
    } 

    // this is just an example, you would need to create the init function 
    // that takes student data and populates a new Student object correctly 
    var student = new Student().init(results); 
    console.log(student); 
} 

要使用RPUSH,你需要,如果你在學生不僅僅是要存儲列表中的其他有其他數據,你的學生分成多個密鑰。基本上列表必須存儲在自己的密鑰中。這通常是通過將列表名稱附加到它所屬的對象關鍵字的末尾來完成的。

我使用了multi操作語法,因此學生一次性添加到緩存中。請注意,如果密鑰不存在,將爲您創建密鑰。

var multi = client.multi().set('studentKey1', 'store any string data'); 
student.lessons.forEach(function(l) { 
    multi.rpush('studentKey1:lessons', l); 
}); 
multi.exec(function (err) { if (err) console.log(err); }); 

然後在最後添加一個新的項目,你會做類似下面的事情。這會將新項目推到列表的末尾。在將新值推入列表末尾之前,不需要獲取該項目。

client.rpush('studentKey1:lessons', JSON.stringify(newItem));