I need help creating a dynamic MongoDB query function that can handle multiple field values, including cases where some fields may be empty strings. In these instances, I want MongoDB to disregard those parts of the query.
Here is my current query function:
function GetReports(args) {
return new Promise((resolve, reject) => {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db(args.organization);
dbo.collection("reports").find(
{
"name": {
$regex: "(?i)" + args.query + "(?-i)"
},
"project_number": {
$regex: "(?i)" + args.project_number + "(?-i)"
},
"category": args.category
}).sort( { "date_sent": -1 }).skip(fetchedDocPerCall * (page - 1)).limit(fetchedDocPerCall).toArray(function (err, result) {
if (err) reject(err);
db.close();
resolve(result);
});
});
});
}
In this function, I aim to retrieve documents based on matching the regex pattern of either the "name" or "project_number" fields, while ensuring an exact match for the "category" field. The challenge lies in handling scenarios where some arguments passed to the function are empty strings. Instead of searching for documents with empty string fields, I want MongoDB to skip those parts of the query. Although I could create numerous functions for each possible combination, I am hoping to streamline this into a single versatile query function.