1

Basically I'm trying to set an object with a given value but I cannot get it to work even though it seems successful. Here is my javascript object;

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

  return newStudent;
}

Later on when I want to obtain the students list I fail as console.log prints "undefined" however the object is not null. My code for insertion to 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);
    });

Two questions;

First, how can I do it properly or is the list structure of Javascript not supported in Redis. Second, if I want to get the item with studentKey1 and insert an item to the back of list how can I accomplist that (how can I utilize RPUSH)?

1 Answer 1

5

If you just want to save the entire Javascript object you need to first convert it into a string since Redis only accepts string values.

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

In the future, if your student object has functions keep in mind that these won't be serialized and stored in the cache. You'll need to rehydrate your object after getting it from the cache.

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

To use RPUSH, you'll need to split your student into multiple keys if you have other data in student other than just the list that you want to store. Basically the list has to be stored in its own key. This is generally done by appending the list name to the end of the object key that it belongs to.

I've used the multi operation syntax so the student is added to the cache in one shot. Note that the keys will be created for you if they don't already exist.

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

Then to add a new item at the end you would do something like the following. This will push a new item onto the end of your list. There is no need to get the item before pushing a new value onto the end of the list.

client.rpush('studentKey1:lessons', JSON.stringify(newItem));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.