I need to run a MongoDB query using JavaScript. Specifically, I am looking to retrieve documents based on two different criteria.
The first condition is as follows:
$or: [
{ "users.username": user.username },
{ buyer: user.username }
]
The second condition is:
$or: [
{ description: { $regex: req.query.q } },
{ buyer: { $regex: req.query.q } },
{ category: { $regex: req.query.q } }
]
To combine these two conditions into a single query, the code snippet used is:
const expenses = await db
.collection("expenses")
.find({
$expr: {
$or: [
{ "users.username": user.username },
{ buyer: user.username }
]
},
$expr: {
$or: [
{ description: { $regex: req.query.q } },
{ buyer: { $regex: req.query.q } },
{ category: { $regex: req.query.q } }
],
},
})
However, running this query results in the following error message:
MongoServerError: Unrecognized expression '$regex'
Can anyone provide guidance on how to resolve this error? Your assistance is greatly appreciated.