Looking to perform a search in my Mongo database which will find all documents that contain a certain string.
The first part of the code splits the user input by spaces, then pushes it to an array.
The second part of the code searches the database to find a match between each item in the array and the firstName field.
I'm trying to use the regex operator to ignore case sensitivity and also see if each element is contained anywhere in the field; i.e. the array element string "f", would yield a match for "frank", "doofus", but not "carlos" - etc.
Here is my code:
var string = 'carlos f sdf';
string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
stringArray.push(string[i]);
}
User.find({firstName: { $regex: {$in: stringArray}, $options: 'i'}}).select("-password").then(user=>console.log(user))
And this is the error I'm getting:
UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ '$in': [ 'carlos', 'f', 'sdf' ] }" at path "firstName" for model "users"
Any ideas what am I doing wrong?