Reputation: 1992
Basic functionality of my app: customers begin to type an email address into a input field and receive auto-suggested results that match the characters they've input.
I've tried implementing this in Mongoose/Mongo in my node app like so:
let customer = await Customer.find({
'email_address': {
$regex: searchQuery
}
})
Important to note that I actually have an index set up for email_address
, in order to improve performance, but I read somewhere that using regex
will void searching through an index? I read the docs on this but I'm just more confused. In any case, the main crux of the question is below:
I know that by doing something like /^exampleEmailAddress/
, it will match results that start with the query (not a wildcard search). This is what I want.
But, how do I do this when the exampleEmailAddress
is a variable I've obtained from req.query
? I've tried:
let customer = await Customer.find({
'email_address': {
$regex: /^`${searchQuery}`/
}
})
which isn't working. I feel like I'm missing something basic here...
Upvotes: 1
Views: 79
Reputation: 10148
You can use Regex
expression for that particular property on your documents. And you can search for case insensitivity using i
as mentioned
customer.find({ "email_address": new RegExp(searchQuery, 'i') }, function (err, task) {
if (err)
res.send(err);
res.json(task);
});
Note. req
and res
may be your request and response objects
Upvotes: 2
Reputation: 23515
You can use the class RegExp
const customer = await Customer.find({
email_address: {
$regex: new RegExp(`^${searchQuery}`),
},
});
Upvotes: 3