torbenrudgaard torbenrudgaard - 2 months ago 10
Javascript Question

Building a json structure for aggregate query dynamically

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...


I 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...


None of them works.

Is there really no smart way to do this?

Answer Source

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...