首页 > 解决方案 > 如何在redis中将对象数组保存为哈希?

问题描述

我正在使用redis将用户信息保存在 nodejs 项目中。用户具有以下结构:

const user = {
    name: 'u1',
    age: 20,
    fav: [{x:0, y:0}, {x:1, y:1}]
}

当我通过它将这些数据保存到redis中时,node-redis它会给我这个警告信息:

client.hmset(userId, user, err => {
    ...
}

node_redis: Deprecated: The HMSET command contains a argument of type Array.
This is converted to "[object Object],[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.

redis上保存的数据是:

127.0.0.1:6379[2]> HGETALL 0
1) "name"
2) "u1"
3) "age"
4) "20"
5) "fav"
6) "[object Object],[object Object]"

我想知道在redis中保存对象数组的最佳方法是什么?

标签: redisnode-redis

解决方案


遇到同样的问题后,我相信保存数据最直接的解决方案是:

client.hmset(userId, JSON.stringify(user), err => {...})

当您检索数据时,您只需要在询问 userId 数据后:

JSON.parse(user)

推荐阅读