$or Operator in Mongoose

$or operator in mongoose is used to perform a logical OR operation on an array of expressions. It helps you in situations when you need to find documents with multiple conditions. Such as creating a search with multiple parameters. It accepts an array of expressions and returns all the documents that satisfy either of the expressions in the array.

Let’s create a mongoose search query that will search a user based on email, mobile, and name. The function will receive a query parameter in the body and our goal is to return all the users whose email or mobile or name matches with the query parameter.

const search = async (req, res, next) => {
const {query} = req.body; //destructring query from body
const foundDocs = await userSchema.find({
$or: [
{email: query}, 
{mobile: query}, 
{name: query}
]
});
res.send({
code: 200,
data: foundDocs,
message: "Found Documents"
});
}

So, that’s a simple mongoose search query. This will return only the matching documents. But what if you need a search that searches for all documents that contain the query word? For example, if query word is equal to you should get all the documents whose email or mobile or name contains a? The simple answer is using regex. Here is a little example

const search = async (req, res, next) => {
const {query} = req.body; //destructring query from body
const foundDocs = await userSchema.find({
$or: [
{email: new RegExp(query, 'i')},
{mobile: new RegExp(query, 'i')}, 
{name: new RegExp(query, 'i')}
]
});
res.send({
code: 200,
data: foundDocs,
message: "Found Documents"
});
}
manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.