Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing and getting boolean with Redis

I'm trying to use Redis to store and get a boolean for my toggle function.

The dependecy what I'm using is redis-js I can set the value false with key to redis but getting the valu from redis is always false.

Say first store the key value to Redis

redis.set('myKey', 'false');

Get the value

let toggle = redis.get('myKey');
toggle = !toggle;

Store

redis.set('myKey', toggle);

Get

const checkStatus = redis.get('myKey');
return checkStatus;

I'm expecting the output will be true -> false if executed the function two times.

like image 304
9years Avatar asked May 04 '19 09:05

9years


People also ask

Can we store Boolean in Redis?

Redis cache backend doesn't allow storing bool values.

Can I store objects in Redis?

Object Storing Procedure. In the Redis, Everything can be stored as only key-value pair format. Key must be unique and storing an object in a string format is not a good practice anyway. Objects are usually stored in a binary array format in the databases.

Can Redis store binary data?

In Redis, we have the advantage of storing both strings and collections of strings as values. A string value cannot exceed 512 MB of text or binary data. However, it can store any type of data, like text, integers, floats, videos, images, and audio files.

What kind of data can be stored in Redis?

Unlike other key-value data stores that offer limited data structures, Redis has a vast variety of data structures to meet your application needs. Redis data types include: Strings – text or binary data up to 512MB in size. Lists – a collection of Strings in the order they were added.


1 Answers

For your toogle to work you've to explicitly check if the value you get is equal to the string 'false'.

let toggle = redis.get('myKey');
toggle = toogle === 'false'

Converting the string 'false' to boolean results to true not false and negating it you get false.

From MDN

All other values, including any object or the string "false", create an object with an initial value of true

Here's an illustration:

const val = 'false'

const toggle = !val; // this is equivalent to !Boolean(val)

const bool = Boolean(val) // get boolean
const negated = !bool // negate
console.log('toggle: ', toggle);
console.log('bool: ', bool); // Boolean("false") gives true
console.log('negated: ', negated);
like image 148
1565986223 Avatar answered Sep 20 '22 04:09

1565986223