首页 > 解决方案 > Redis Hget 对持有错误类型值的键抛出 WRONGTYPE 操作

问题描述

我正在使用 nodeJs 来获取 redis 键字段中的值。像这样的东西:

let result = await redisM.hget('aaa:bbb', 'profiles');

我正在寻找的值是一个对象,但我不断收到“针对持有错误类型值的键的 WRONGTYPE 操作”异常,如果从 hget 方法打印错误,我得到:

------------------------------------
{ ReplyError: WRONGTYPE Operation against a key holding the wrong kind of value
    at parseError (/PATH123/node_modules/redis-parser/lib/parser.js:193:12)
    at parseType (/PATH123/node_modules/redis-parser/lib/parser.js:303:14)
  command: 'HGET',
  args: [ 'aaa:bbb', 'profiles' ],
  code: 'WRONGTYPE' }
------------------------------------

如果我刷新 redis db,运行HGET aaa:bbb profilesin redis-cli 我会得到(nil)结果,但这不应该抛出这个错误,或者是吗?

此外,如果我通过 redis-cli 为该键设置一个值,我可以在之后使用 HGET 获取它的值:

HSET sip_profiles profiles {}
(integer) 1

HGET sip_profiles profiles
"{}"

不明白为什么它适用于 redis-cli 但不适用于节点......即使是空键......

使用的节点依赖: "redis": "^2.8.0"

标签: node.jsredisredis-cli

解决方案


我遇到了同样的问题,我设置了一个字符串键而不是哈希键,然后当我尝试检索字符串键的键时,我得到了错误。

解决方案:确保所需的密钥是Hash类型,然后 hget 不会失败

>> redis.set 1,1
=> "OK"
>> redis.hkeys 1
Operation against a key holding the wrong kind of value: Expected Hash at 1.
Redis::CommandError: WRONGTYPE Operation against a key holding the wrong kind of value
from /onelogin/src/vendor/bundle/gems/fakeredis-0.5.0/lib/redis/connection/memory.rb:991:in `data_type_check'
from /onelogin/src/vendor/bundle/gems/fakeredis-0.5.0/lib/redis/connection/memory.rb:213:in `hkeys'
from /onelogin/src/vendor/bundle/gems/fakeredis-0.5.0/lib/fakeredis/command_executor.rb:10:in `send'
from /onelogin/src/vendor/bundle/gems/fakeredis-0.5.0/lib/fakeredis/command_executor.rb:10:in `write'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:257:in `write'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:236:in `io'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:255:in `write'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:214:in `process'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:208:in `each'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:208:in `process'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:353:in `ensure_connected'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:207:in `process'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:292:in `logging'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:206:in `process'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis/client.rb:112:in `call'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis.rb:1995:in `hkeys'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis.rb:37:in `synchronize'
from /usr/local/lib/ruby/1.8/monitor.rb:242:in `mon_synchronize'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis.rb:37:in `synchronize'
from /onelogin/src/vendor/bundle/gems/redis-3.2.1/lib/redis.rb:1994:in `hkeys'
from (irb):36>> 

推荐阅读