Looking to create a query that matches fields with data in them.
Here is an attempt:
var matchStr = {};
if (received.user) {
matchStr = { "_id": { "$regex": received.user, "$options": "i" } };
}
if (received.name) {
matchStr += { "name": { "$regex": received.name, "$options": "i" } };
}
if (received.phone) {
matchStr += { "phone": { "$regex": received.phone, "$options": "i" } };
}
usersTable.aggregate([
{
$match: { matchStr }
}, etc...
I also tried this:
var matchStr = [];
if (received.user) {
matchStr.push( { "_id": { "$regex": received.user, "$options": "i" } } );
}
if (received.name) {
matchStr.push( { "name": { "$regex": received.name, "$options": "i" } } );
}
if (received.phone) {
matchStr.push( { "phone": { "$regex": received.phone, "$options": "i" } } );
}
usersTable.aggregate([
{
$match: { matchStr }
}, etc...
Unfortunately, neither of these methods worked as intended.
Is there a more clever approach to achieve this?