Tuesday, 16 May 2017

nodejs how to dynamically manipulate your MongoDB aggregate in your controller?

I have a very loooong aggregate in my nodejs controller:

agentSaleModel.aggregate([
    {
        $match: {
            $and: 
            [{ 
                _id: { $in: req.body.propertyID },
                active : true
            }]
        }
    }, etc....

And it works great when I got elements in my req.body.propertyID like ["property01","property02"] etc...

My problem is that I also want the aggregate to work when there are nothing in req.body.propertyID. (when its blank) - and then get all records.

This does not work:

agentSaleModel.aggregate([
    {
        $match: {
            $and: 
            [{ 
                _id: { $in: '' },
                active : true
            }]
        }
    }, etc....

So rather than doing an "if" with two huge sets of almost identical code:

if (req.body.propertyID) {
   ...the entire aggregate... 
} else {
   ...the entire aggregate minus the _id: { $in: req.body.propertyID },... 
}

Is there a smarter way to do this?



via torbenrudgaard

No comments:

Post a Comment