检查每个单词是否存在于数据库中

问题

我需要通过search每个单词的mongoDB集合来检查每个string是否拼写正确。

  1. 做最less量的数据库查询
  2. 每个句子的第一个单词必须是大写的,但这个单词在字典中可以是大写或小写。 所以我需要为每个单词区分大小写匹配。 只有每个句子的第一个单词应该是敏感的。

示例string

This is a simple example. Example. This is another example. 

字典结构

假设有一个像这样的字典集合

 { word: 'this' }, { word: 'is' }, { word: 'a' }, { word: 'example' }, { word: 'Name' } 

就我而言,这本字典中有10万字。 当然,名字以大写forms存储,动词以小写forms存储,等等。

预期结果

simple词和another词应该被认为是拼写错误的词,因为它们不存在于DB中。

在这种情况下,一个包含所有现有单词的数组应该是: ['This', 'is', 'a', 'example']This是大写字母,因为它是一个句子的第一个单词; 在DB中它是以小写的方式存储的。

我到目前为止的尝试(更新)

 const sentences = string.replace(/([.?!])\s*(?= [AZ])/g, '$1|').split('|'); let search = [], words = [], existing, missing; sentences.forEach(sentence => { const w = sentence.trim().replace(/[^a-zA-Z0-9äöüÄÖÜß ]/gi, '').split(' '); w.forEach((word, index) => { const regex = new RegExp(['^', word, '$'].join(''), index === 0 ? 'i' : ''); search.push(regex); words.push(word); }); }); existing = Dictionary.find({ word: { $in: search } }).map(obj => obj.word); missing = _.difference(words, existing); 

问题

  1. 不敏感的匹配不能正常工作: /^Example$/i会给我一个结果。 但在existing将会是原来的小写的example ,这意味着Examplemissingarrays。 所以不区分大小写的search是按预期工作,但结果数组有一个mismatch。 我不知道如何解决这个问题。
  2. 优化代码可能吗? 由于我使用了两个for-the-loop和一个difference

这是我如何面对这个问题:

  • 使用正则expression式来获取数组中的空格(包括“。”)后的每个单词。

     var words = para.match(/(.+?)(\b)/g); //this expression is not perfect but will work 
  • 现在,使用find()将您的集合中的所有单词添加到数组中。 可以说这个数组的名字是wordsOfColl

  • 现在检查是否你的文字是你想要的

     var prevWord= ""; //to check first word of sentence words.forEach(function(word) { if(wordsOfColl.toLowerCase().indexOf(word.toLowerCase()) !== -1) { if(prevWord.replace(/\s/g, '') === '.') { //this is first word of sentence if(word[0] !== word[0].toUpperCase()) { //not capital, so generate error } } prevWord = word; } else { //not in collection, generate error } }); 

我还没有testing过,所以请让我知道如果有问题的话。 或者我错过了你的一些要求。

更新

作为问题的作者build议他不想在客户端加载整个集合,您可以在服务器上创build一个方法,返回一个字数组,而不是访问集合的客户端访问。