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?
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}}, ...