Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
How do I check if the value of a MongoDB field is in a string?

So I'm using mongoose and MongoDB to create a chatbot, and I want to be able to see if any of the documents match any part of what the user said without it having to be an exact match. I know that if the input string was only part of the element I could just use the $regex operator, but in my case the element is only part of the input string. Here's what I have so far:

app.post('/mood',(req,res) => {
  const str = req.body.mood.toLowerCase();
  var arr = str.split(/([_\W])/);
  console.log(arr);
  Words.findOne({words: {$in: arr}},(err,data) => {
    if (err) {
      res.json({
        status: 'failure',
        reason: 'Server error.',
        prompt: null
      });
      console.log(err);
      return;
    }
    if (!data || data==null || data==[]) {
      res.json({
        status: 'failure',
        reason: 'We don\'t have a response to that yet. Would you like to make one?',
        prompt: 'make'
      });
      return;
    }
    console.log(data.words);
    var reply = data.responses[Math.floor(Math.random()*data.responses.length)].phrase;
    res.json({ status: 'success', reply});
  });
});

but that only works for single word fields like "hello," not phrases like "how are you" or "my name is." So if someone says "how are you doing?" it won't come up for "how are you" if I use the whole string OR if I split it up into "how", "are", "you", "doing", and "?". How do I make it see if the entire string from the database matches any part of the string from the user?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can build a regex from the string:

  const str = req.body.mood.toLowerCase();
  let regex = new RegExp(str.split(/[_\W+]/).filter(str => {
    return /^[\w]+$/.test(str)
  }).join('|'))
  console.log(regex.toString());

The regex for string "how are you doing?" will be /how|are|you|doing/. We do not need to worry about escaping characters when building the regex since we have only alpha chars.

Now you can use that regex in your query to find the user supplied words in all your words fields:

  Words.findOne({words: {$regex: regex}}, ...
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda