Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda