skip to Main Content

The Redis command HMSET has been deprecated since version 4. They suggest using HSET instead. But when trying that I get a different deprecation warning.
I was using: db.hmset('key', {a: 1, b: 'c'}). Now I tried to replace it with db.hset but that triggers:

node_redis: Deprecated: The HSET command contains a argument of type Object.
This is converted to "[object Object]" by using .toString() now and will return an error from v.3.0 on.
Please handle this in your code to make sure everything works as you intended it to.

What is the correct way to store an object in a Redis database?

The documentation for Redis HSET states: ‘As of Redis 4.0.0, HSET is variadic and allows for multiple field/value pairs.’ I want to store the whole object as it would be using hmset in the database, not its string representation.

3

Answers


  1. Well it seems that the second argument of hset must be a string. If it’s not .toString will be applied to it. But as it will return "[object Object]" in your case, the warning triggers. Maybe use JSON.stringify({a: 1, b: 'c'}) as parameter instead

    Login or Signup to reply.
  2. as described here, redis client dose not support objects in a command arguments.

    To easily store an object in redis you can do:

    db.hset('key', ...Object.entries({a: 'a', b: 'b'}), (err) => {
      // ...
    });
    

    note that it’ll ignore Symbol keys, and work only with "flat objects".

    Login or Signup to reply.
  3. For those using Typescript, the second argument of hSet can be an array of strings of this kind [‘k1’, ‘v1’, ‘k2’, ‘v2’,…]. So the following code works:

    const obj: Record<string, string | number> = {a: 'a', n: 1};
    await client.hSet('key', [...Object.entries(obj).flat()]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search