首页 > 解决方案 > 如果使用空字符串传递,如何使 mongoose.find 不返回所有数据

问题描述

我在每个视频数据上都有标题名称,并编写了一个搜索 api,它将获取与标题名称匹配的视频数据

    exports.findbytitle = (req, res) => {
      let userPattern = new RegExp(req.body.title, "i");
      Videos.find({ title: userPattern })
        .then((video) => {
          res.send({ success: true, video });
        })
        .catch((err) => {
          res.send({ success: false, err });
        });
    };

这里的问题是如果userPattern匹配我得到正确的视频,但如果userPattern是空字符串示例:("title": "")我得到所有视频而不是错误。userPattern如果作为空字符串传递,我应该进行哪些更改才能得到错误?

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


如您所知,仅当标题为空时,为什么不在查询前添加条件?

if(!req.body.title) {
   return res.send({ success: false, err: new Error("Not found")})
}

推荐阅读