Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!