0

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?

4
  • 1
    Regex not use with in Commented Jan 6, 2020 at 14:19
  • Thanks, just saw the documentation on that... docs.mongodb.com/manual/reference/operator/query/regex/… Not super familair with Javascript regular expression syntax - any ideas how I can accomplish what I'm trying to do with that? Commented Jan 6, 2020 at 14:25
  • 1
    Your problem solved ?? Commented Jan 6, 2020 at 14:41
  • Not yet - need to do a little research on how to use JavaScript regular expressions, and how I can apply them here. The mongo documentation gives some guidance, but I'll need to mess around. If you have any recommendations let me know, otherwise thanks for the help. Commented Jan 6, 2020 at 14:47

3 Answers 3

1

We can use or function for getting result

User.find({
    "$or": [{
        firstName: { $regex: 'carlos', $options: 'i'}
    }, 
   {
        firstName: { $regex: 'f', $options: 'i'}
    },
   {
        firstName: { $regex: 'sdf', $options: 'i'}
    }]
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, what if the string is dynamic, an input sentfrom the browser - i.e. you don't know how many elements will be in the array.. var string = req.query.userSearch Could you loop through that somehow?
0

You can use '|' as an 'OR' operator for the regular expressions.

db.collection.find({ "firstName": { "$regex": "^carlos$|^f$|^sdf$", $options: "i" } })

The above query should work for you if you want to match the exact values.

If you want to match for those documents which contain given strings then use the below query.

db.collection.find({ "firstName": { "$regex": "carlos|f|sdf", $options: "i" } })

And as you asked about dynamic length input then you just have to Join all those string with '$|^' and once all the strings are joined you can append it with '$' and prepend it with '^' for the exact match in case of contain you just need to join all the string with '|' operator.

Comments

0

Thank you for the responses everyone. Below is how I solved the problem

var string = req.params.postParams
string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
}
var regex = stringArray.map(function (e) { return new RegExp(e, "i"); });

User.find({firstName: { $in: regex }).select("-password").then(user=>console.log(user))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.