如何在Redis中将对象数组保存为哈希?

问题描述 投票:0回答:1

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

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

当我通过node-redis将这些数据保存到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中保存对象数组的最佳方法是什么?

redis node-redis
1个回答
0
投票

遇到相同的问题后,我认为保存数据的最直接的方法是:

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

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

JSON.parse(user)
© www.soinside.com 2019 - 2024. All rights reserved.