Steyrox
Steyrox

Reputation: 1

Mongodb use or skip a $match based on a condition

Im developping a web apllication and i couldnt manage to use a $match after a condition so basicly what i wan'to do, if the user is an admin i skip the $match and if the user is not an admin i match data based in the logged in user.

This is was my attempt:

{ $cond: { if: currentuser != Admin, then:{ $match: { state: currentuser } } } },

But it didn't work and i got this error :

MongoServerError: Unrecognized pipeline stage name: '$cond'

and this is the whole code :

    exports.allsstates = async (req, res) => {
    
    currentuser = JSON.parse(atob(req.headers.authorization.split('.')[1])).role;
    
    try {
        const allstate = await Users.aggregate(
            [

                {
                   
                         $cond:{ if:{ $eq: [currentuser, 'Admin']} ,then:{  $match: { state: currentbase }}}   ,
                    
                },
{
    $lookup:
                    {
                        from: "types",
                        localField: "type",
                        foreignField: "_id",
                        as: "type"
                    }
                },
                {
                    $set: {
                        type: "$type.type",
                    }
                },
   { $match: { type: "x" } },
   { $match: { situation: "y" }}
          ]
        )

        res.json(allstate);
    }
    catch (err) {
        console.log(err);
        res.status(500).json({ message: 'Internal server error' });
    }
    }

Upvotes: 0

Views: 604

Answers (1)

Buzz Moschetti
Buzz Moschetti

Reputation: 7578

You can programmatically construct the pipeline. For clarity, start with the "constant" part i.e. the stages you always run, then use if/then/else to prepend a $match:


var pipeline = [
{$lookup: {
    from: "types",
    localField: "type",
    foreignField: "_id",
    as: "type"
}},
{$set: { type: "$type.type" }}, 

{$match: { type: "x", situation: "y" }} // 2 $match stages combined into 1 for efficiency...
          
];

if(currentuser != "admin") {
    // Prepend a $match condition:
    pipeline.unshift({$match: {state: currentuser}});
}
Users.aggregate(pipeline);

Upvotes: 1

Related Questions