node.js - 如何在 Redis 中的对象中搜索值?

标签 node.js redis

我是 Redis 和 Nodejs 的新手,我看过 this教程,我正在尝试按名称搜索用户,

这是对象,当我传递 id 时从 redis 返回:

  {
    first_name: '‪john',
    last_name: 'doe',
    email: 'john@gmail.com',
    phone: '543313305',
    id: 'user001' 
   } 

这是搜索的功能:

app.post('/user/search',function (req,res,next) {
let id = req.body.id;

client.hgetall(id ,function(err,obj){
    if(!obj){
        res.render('searchusers',{
            error:"user doesn't exist",

        });

    } else {
        obj.id = id
        console.log(obj);
        res.render('details',{
            user:obj, });
    }
   });
});

我尝试通过以下方式将按 id 搜索替换为按 first_name 搜索:

首先,我将字段名称更改为“first_name”而不是“id”

<h1>Search Users</h1>
{{#if error}} <span>{{error}}</span>{{/if}}
 <form class="form-inline" method="POST" action="/user/search">
<div class="form-group">
    <input type="text" name="first_name" placeholder="Search" class="form-
  control">
</div>
<input type="submit" class="btn btn-primary" value="Search">

然后我在 app.js 中更改了它;

app.post('/user/search',function (req,res,next) {
let first_name = req.body.first_name;

client.hgetall(first_name ,function(err,obj){
    if(!obj){
        res.render('searchusers',{
            error:"user doesn't exist",

        });

    } else {
        obj.first_name = first_name
        console.log(obj);
        res.render('details',{
            user:obj, });
    }
   });
});

最佳答案

hgetall您在该方法的搜索功能中使用的方法通过键查找散列,在本例中为用户 ID,并从 Redis 返回散列的所有字段。

没有搜索散列字段的功能。如果您需要能够从名字映射到用户,则需要使用集合等数据结构手动构建二级索引,这样您就可以从名字映射到具有该名字的用户。

关于node.js - 如何在 Redis 中的对象中搜索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225051/

相关文章:

oracle - 如何在 Windows 中连接 Oracle 11g 和 nodejs?

node.js - Node JS : How to run a task for every 30 minutes , 包括现在

node.js - Node.js 中的缓冲区比较

docker - redis.conf 在官方 docker 镜像中的位置是什么?

node.js - sails postgresql 多对多关联不起作用

Redis读写并发

hash - Redis 按字段和值进行哈希搜索

redis - 在一天中的特定时间备份redis

database - 电子邮件数据库架构

node.js - 如何在NeptuneDB中进行分页以实现高性能