简体   繁体   中英

How to create a mongoose query that supports empty values and returns all

The user has a form to fill and search for documents in a mongoDB collection. The user doesn´t need to fill all inputs of the form, but the ones that the user has filled need to be queried together. The inputs the user has not filled go to the backend as "" an empty string.

my query goes like this:

let cf = await Cf.find({
            $and: [
                {userId: userId},
                {$and: [
                    {name: name == '' ? null : name},
                    {catg: catg == '' ? null : catg},
                    {value: value == '' ? null : value}
                ]}
            ]
        });

So, for the query i set a condition that if the values are equal to "" than I change it to null , but mongoose is actually searching for null values. Is there some sort of empty placeholder that gets back all documents? If I leave as an empty string or change it to undefined it also does not work.

what would be the best approach if the user has left some empty fields?

UPDATE

Using mickl's logic and a few tweaks, it worked perfectly. here is the final result.

        let query = {
                    $and: [
                        {userId: userId}
                    ]
                };

        let subQuery = [];

        if (name !== ''){
            subQuery.push({name: name})
        };

        if (catg !== ''){
            subQuery.push({catg: catg})
        };

        if (value !== ''){
            subQuery.push({value: value})
        };

        if( name !== '' || catg !== '' || value !== ''){
            query.$and.push({$and: subQuery})
        };

        let cf = await Cf.find(query);

If the value is empty then it cannot be included in your query, try to apply this query building logic before you hit .find() :

 let userId = 1, name = 'a', catg = '', value = ''; let query = { userId: userId }; if(name !== ''){ query.name = name; } if(catg !== ''){ query.catg = catg; } if(value !== ''){ query.value = value; } console.log(query);

let cf = await Cf.find(query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM