最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace deprecated HMSET in in node.js REDIS - Stack Overflow

programmeradmin0浏览0评论

The Redis mand 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 mand 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.

The Redis mand 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 mand 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.

Share Improve this question edited Feb 4, 2021 at 16:35 Pavel Dohnal asked Feb 4, 2021 at 14:58 Pavel DohnalPavel Dohnal 211 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

as described here, redis client dose not support objects in a mand 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".

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()]);

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

发布评论

评论列表(0)

  1. 暂无评论