Skip to content

Instantly share code, notes, and snippets.

@jeffandersen
Created November 6, 2014 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffandersen/3fbaf323cd001567b058 to your computer and use it in GitHub Desktop.
Save jeffandersen/3fbaf323cd001567b058 to your computer and use it in GitHub Desktop.
Using a single hash key to store multiple values
// We want to store all three of these together
var one = 1;
var two = 2;
var three = 3;
// Redis only accepts a single value for a key
// so we must group the values together, we can use an object:
var data = {
one: one,
two: two,
three: three
};
// But we have an object of data, Redis only accepts strings for values
// we can use JSON to turn the object into a string:
var stringData = JSON.stringify(data);
// Now we can store it in the hash key:
client.hset('my-data', 'key-name', data, function(err) {
if (err) throw err;
// If we retrieve the value:
client.hget('my-data', 'key-name', function(err, data) {
if (err) throw err;
// Data is actually a string right now, which we can't use easily
// to grab the one/two/three values, so we parse it:
var dataObject = JSON.parse(data);
// Now you can log out the individual values:
console.log(dataObject.one, dataObject.two, dataObject.three);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment