简体   繁体   English

如何创建支持空值并返回所有值的猫鼬查询

[英]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.用户有一个表单来填写和搜索 mongoDB 集合中的文档。 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.因此,对于查询,我设置了一个条件,如果值等于 "" 则将其更改为null ,但猫鼬实际上是在搜索空值。 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.如果我保留为空字符串或将其更改为undefined它也不起作用。

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.使用mickl 的逻辑和一些调整,它完美地工作。 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() :如果该值为空,则它不能包含在您的查询中,请在点击.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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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