Store Javascript objects in Redis with Node.js the right way

This is part 2 of my Node/Redis series. You can read Part 1, Dancing around strings in Node.js and Redis, Part 3, Using the Redis multi object in Node.js for fun and profit, Part 4 Keeping track of account subscriptions with Redis and Node.js Part 5 Managing modularity and Redis connections in Node.js, Part 6 Redis, Express and Streaming with Node.js and Classic Literature(?), Part 7 Untangling Redis sort results with Node.js and lodash and Part 8 Redis, set, node.

Hey! If you’re reading this, maybe you want to go to RedisConf 2018 for free?

On the face of it, a Redis hash is fairly similar to a Javascript object used for data storage. You have a key, fields and values. Here is some data represented in roughly the same way between Redis and Javascript:

HSET “a-test” “name” “Kyle Davis”
HSET “a-test” “address” “123 Main Street”
aTest = {
name : ‘Kyle Davis’,
address : ‘123 Main Street’
aTest = {
name : { first : ‘Kyle’, family : ‘Davis’},
address : ‘123 Main Street’
#bad - don't do this
HSET "a-test" "name" "{\"first\":\"Kyle\",\"family\":\"Davis\"}"
HSET "a-test" "address" "123 Main Street"

Best of both worlds

So then, aside from banning nested objects, how do you get the best of both worlds?

aTest = {
"name.first" : ‘Kyle’,
"" : ‘Davis’,
"address" : ‘123 Main Street’
HSET “a-test” “name.first” “Kyle”
HSET “a-test” “” “Davis”
HSET “a-test” “address” “123 Main Street”
HGET "a-test" ""
sort myTestList BY *->name.first ALPHA DESC GET *->address GET *->name.first

The Good, Bad, Ugly

Flat is not perfect. I’m not crazy about how it handles arrays. You get into the same situation you have with JSON — Redis doesn’t really understand what is going on and thus won’t be able to retrieve and manipulate it directly. I don’t have the answer for how to deal with that kind of situation, but it isn’t perfect as is.

Still struggling to store stuff in Redis the right way?

Drop me a line and we can talk about how I might be able to help you get on the right Node / Redis foot.

Developer of things. Node.js + all the frontend jazz. Also, not from Stockholm, don’t do UX. Long story.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store