Using SQL ( LIKE && OR ) statement in mongoose

ยท

2 min read

Hey there, this happens to be the first post I would be sharing throughout my journey while building https://codemarka.dev.

Problem: I wanted to fetch users based on either email or username, this means that in the input element, you should type an email address or a username and , then we do an API call with that value and an array of users get returned if there be any match.

Solution: This is a single query to my DB as you can find below.

const { emailOrUsername} =  req.params;
const regex = `.*${emailOrUsername}.*`;

User.find({ $or:[ {"username": { $regex: regex} },  { "email" : {$regex: regex} } ]},{username: true,kid: true, _id: false} ,(err, user) => {
        if(user && user.length > 0){
            return successResponse(res, user);
        } else {
            return successResponse(res,[]);
        } 
    });

EXPLANATION:

The $or is a keyword ( not sure if this is the word ) which is means, hey mongoose, find me a row(s) where the username field or email field matches any value provided.

$regex of course means we are providing a regular expression string.

lastly,({ username: true, kid: true,_id: false } I am specifying specific fields to return because of obvious reasons. Setting a value to false would omit that field for a record.

This query takes 30ms at most on my 8Gig ram, 255 SSD, i5 machine.

We meuuuvvv!!!