我是 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/