Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb Mongoose$文本搜索(如果为空)_Mongodb_Mongoose - Fatal编程技术网

Mongodb Mongoose$文本搜索(如果为空)

Mongodb Mongoose$文本搜索(如果为空),mongodb,mongoose,Mongodb,Mongoose,我有一个这样的疑问 Resource.find({ isResource:true, $text: {$search: req.query.search} }).lean().exec(function(err, resources){ if(err){ next(err); return; }else{ res.send(res

我有一个这样的疑问

Resource.find({
            isResource:true,
            $text: {$search: req.query.search}
        }).lean().exec(function(err, resources){
        if(err){
            next(err);
            return;
        }else{
            res.send(resources);
        }
    });
有时用户不想输入搜索查询,因此只会返回所有正确的资源。但是,如果我为$search属性提供空值,就会得到一个错误。如果我提供一个空字符串,它将不返回任何项目,因为它正在使用空字符串进行搜索


当req.query.search为空或null时,$search是否有条件地处理null值而不必添加另一个查询来忽略$text字段?

否,但通过编程方式组合查询,在查询中忽略该术语很简单:

let query = { isResource: true };
if (req.query.search) {
    query.$text = {$search: req.query.search};
}
Resource.find(query).lean().exec(function(err, resources){
    if(err){
        next(err);
        return;
    }else{
        res.send(resources);
    }
});

先生,在集合区怎么样?我试过你的答案,但还是没有答案