猫鼬:使用正则表达式查询全名 [英] Mongoose: query full name with regex

查看:85
本文介绍了猫鼬:使用正则表达式查询全名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码通过名字或姓氏搜索用户:

I'm using the following code to search a user either by first or last name:

var re = new RegExp(req.params.search, 'i');

User.find()
    .or([{ firstName: re }, { lastName: re }])
    .exec(function(err, users) {
        res.json(JSON.stringify(users));
    });

如果search等于'John''Smith',则效果很好,但对于'John Sm',则不适用.

It works well if search equals 'John' or 'Smith', but not for 'John Sm'.

任何线索如何完成这种查询?

Any clue how to accomplish this kind of query?

谢谢!

免责声明:该问题最初出现在

Disclaimer: This question originally appeared on the comments of this previous question 3 years ago and remains unanswered. I'm starting a new thread because 1) It wasn't the main question and 2) I consider this is interesting enough to have its own thread

假定数据库包含两个记录:John SmithJohn Kennedy.

Suppose the database contains two records: John Smith and John Kennedy.

  • 查询John应该同时返回John SmithJohn Kennedy
  • 查询John Sm应该仅返回John Smith
  • Querying John should return both John Smith and John Kennedy
  • Querying John Sm should return only John Smith

推荐答案

用单词分隔搜索词,然后使用交替运算符('|')分隔它们.

Separate the search term by words, and separate them using an alternation operator ('|').

var terms = req.params.search.split(' ');

var regexString = "";

for (var i = 0; i < terms.length; i++)
{
    regexString += terms[i];
    if (i < terms.length - 1) regexString += '|';
}

var re = new RegExp(regexString, 'ig');

对于输入'John Smith',这将创建一个类似于/John|Smith/ig的正则表达式.当输入只是'John Sm'

For the input 'John Smith', this will create a regex which looks like /John|Smith/ig. This will return true for individual words as well as work when the input is just 'John Sm'

您可以使用此正则表达式,以获得一种更适合您的需求.

You can play around with this regex to get one more suited to your needs.

这里的问题是您的姓名字段是分开的.在这种情况下,对两个字段应用相同的正则表达式将不会得到所需的结果.正则表达式需要使用完整名称应用于同一字段.

The problem here is that your name fields are separate. In this case, applying the same regex to both fields will not result the results that you want. The regex needs to be applied to the same field with the complete name.

可能的解决方案是使用聚合:

A possible solution is using aggregation:

User.aggregate()
    .project({fullName: {$concat: ['$firstName', ' ', '$lastName']}})
    .match({fullName: re})

这篇关于猫鼬:使用正则表达式查询全名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆