通过 node.js 应用程序在 redis 中保存嵌套哈希 [英] Save nested hash in redis via a node.js app
问题描述
我正在使用 node_redis 并且我想保存如下结构:
I'm using node_redis and I'd like to save a structure like:
{
users :
"alex" : { "email" : "alex@gmail.com",
"password" : "alex123"},
"sandra" : { "email" : "sandra@gmail.com",
"password" : "sandra123"},
...
}
目前,我为每个用户创建一个 JSON 对象:
Currently, for each user I create a JSON object:
jsonObj = { "email" : "alex@gmail.com",
"password" : "alex123"}
然后做一个
db.hmset("alex", JSON.stringify(jsonObj))
是否可以将此结构嵌入到另一种结构中(用户结构?)我怎么能用这个结构设置 users["alex"] ?
Is it possible to embedded this strucute in another structure (the users one ?) How could I set users["alex"] with this structure ?
推荐答案
据我所知,Redis 中没有对嵌套结构的原生支持,但可以使用 set+hash(类似于
As far as I know there isn't native support for nested structures in Redis, but they can be modeled for example with set+hash (similar to hierarchical trees). Hashes are probably best suited for storing fields and values of single JSON object. What I would do is to store each user with a prefix (which is a Redis convention), for example:
db.hmset("user:alex", JSON.stringify(jsonObj));
然后使用 sets 使用名为 users的键将用户分组为一组代码>.然后,我可以通过 smembers 命令获取所有用户密钥,并使用 hgetall.
and then use sets to group users into one set with a key named users
. I can then get all of the users keys by smembers command and access each of them individually with hgetall.
这篇关于通过 node.js 应用程序在 redis 中保存嵌套哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!