javascript - Ignore field in $match stage in aggregation pipeline

I have a GraphQL resolver which takes an argument test of type Boolean. Inside this resolver, I use Mongoose to carry out a MongoDB aggregation returning documents from my users collection based on the value of the test argument.

This is what my GraphQL testUsers resolver looks like:

Query: {
    testUsers: async (root, args, context) => {
        return await User.aggregate([
            {
                $match: {
                    test: args.test
                }
            }
        ])
    }
}

Over here, args.test may be true, false or undefined. Handling the true and false cases is just a matter of passing it directly but I want to return all users (irrespective of the value of test) if args.test is undefined.

Is there a value I can pass for test in the $match stage, which will not take the test field into consideration?

1 Answer

  1. Kenneth- Reply

    2019-11-13

    You can do something like this

    testUsers: async (root, args, context) => {
        let match = { test: args.test }
        if(typeof args.test === 'undefined') {
          match = {}
        }
        return await User.aggregate([
            {
                $match: match
            }
        ])
    }
    

    You can take a let variable and change its value if args.test is undefined

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>