JS:对象值取决于regEx匹配

时间:2017-12-18 02:55:57

标签: javascript regex mongodb reactjs

数组中有一些对象如下:

const result = [
  {
    "_id": "Dn59y87PGhkJXpaiZ",
    "title": "Something",
    "synonyms": [ "Anything", "else" ]
  },
  { ... }
]

我通过执行此操作获得此结果:

Content.find({
  $or: [
    { title: { $regex: new RegExp(term, 'i') } },
    { synonyms: { $regex: new RegExp(term, 'i') } }
  ]
}).toArray()

如您所见,我正在按给定的搜索词搜索标题(字符串)或同义词(数组)元素。 因此,搜索someany会给我第一份文件作为结果。

在我的组件中,我按以下方式输出数据:

render () {
  return result.map((link, index) => {
    return <Dropdown.Item
      text={link.title}
      key={index}
    />
  })
}

但是,如果我正在搜索Something(term),那么我现在得到下拉项的输出any。对于用户来说这没有意义。

当然any应该为我提供输出Anything,而some应该为我提供输出Something。 在此示例中,您还可以搜索thing,我希望有两个输出元素(一个结果文档):AnythingSomething

我不太确定如何修改代码以获得此结果。我认为修改的最佳位置应该是react组件(输出) - 而不是服务器请求结果。

1 个答案:

答案 0 :(得分:0)

You could issue two separate queries on the server side to maintain clearly which part of your document was matched. This would ensure that for the doc which matches using synonyms was not used to return title.

const matchingTitles = Content.find(
    { title: { $regex: new RegExp(term, 'i') } }
}, {title: 1} ).toArray().map(x => x.title);

const matchingSynonyms = Content.find(
    { synonyms: { $regex: new RegExp(term, 'i') } }
}, {synonyms: 1} ).toArray().map(x => x.synonyms).reduce((x, y) => x.concat(y), []);

return Array.from(new Set([...matchingTitles, ...matchingSynonyms]));

I fetch the strings separately using two queries and then take the set union of them.

And on client side you could use these strings directly to display the search result.