I want to build a query matching the fields that has data in them.
I tried this:
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...
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...
You shouldn't use an array inside $match
, the correct way is to use an object and assign to it:
var matchStr = {};
if (received.user) {
matchStr["_id"] = { "$regex": received.user, "$options": "i" };
}
//etc...
usersTable.aggregate([
{
$match: matchStr
},
//etc...