【问题标题】:Angular & Mongo query , return result closely equal to related to the search keywordAngular & Mongo 查询,返回结果与搜索关键字密切相关
【发布时间】:2020-07-15 07:40:07
【问题描述】:

如果 text(firstname) == 'Eric' ,它应该返回 results 。知道如何调整我的代码以按照示例中的预期返回结果吗?

我在前端使用 angular。

#预期结果(这将是结果的顶部)

Eric Gluthner
Eric Lecher
Erick Laspin

#和其他带有 eric 的名字会不那么优先

Derick Ramp
Daniel Ericto
Raerick Fouler

#代码

getData(text: string): Observable<Identity[]> {
  const search_query = {
    query: {
      $or: [
        { firstName: { $like: text } },
        { email: { $like: text } },
      ],
      status: 1,
      $sort: {
        firstName: 1
      },
      // $limit: 5,  
    }
  };

【问题讨论】:

标签: javascript angular mongodb typescript


【解决方案1】:

使用$regex 模式匹配

getData(text: string): Observable<Identity[]> {
  const search_query = {
    query: {
      $or: [
        { firstName: { $regex: RegExp('^' + text) } },
        { email: { $like: text } },
      ],
      status: 1,
      $sort: {
        firstName: 1
      },
      // $limit: 5,  
    }
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 2016-05-13
    • 2021-01-19
    • 2017-02-21
    • 1970-01-01
    相关资源
    最近更新 更多