猫鼬查找或多列不起作用

Mongoose find or multiple columns not working

如果关键字在 category.title 中匹配,则它会给出结果,否则它不会与任何其他字段匹配。有人能告诉我这里有什么问题吗? 还尝试了 NewsModel.find().or(filters) 没有 $or 键,仍然无法正常工作。

  let filters = {};

  if (keyword) {
    filters = {
      $or: [
        {
          title: keyword,
        },
        {
          shortDescription: keyword,
        },
        {
          detailDescription: keyword,
        },
        {
          "category.title": keyword,
        },
      ],
    };
  }

  const response = await NewsModel.find(filters);

猫鼬:6.3.0

更新:添加了数据库集合

 {
        "_id": "625b83518b1eaedc58a74196",
        "title": "Moon Knight",
        "shortDescriptipn": "Embrace the chaos.",
        "detailDescription": "When Steven Grant, a mild-mannered gift-shop employee...",
        "category": [
            {
                "_id": "625b7dfd00e7f082f6d8d9fb",
                "title": "Entertainment"
            }
        ],
        "createdAt": "2022-04-17T03:02:41.353Z",
        "updatedAt": "2022-04-17T03:02:41.353Z",
        "__v": 0
    }

如果我搜索 Entertainment,我得到结果,但如果我搜索 Moon Knight,我得到空数组。

您可以使用此代码使其工作,而且您在数据库中拼错了 shortDescriptipn

我所做的是,我在正则表达式搜索中使用了 $or 关键字,因此您不需要编写完整的字符串,如果它包含字符串的那部分,它将 return 文档而不是一个严格的完全匹配案例,我还添加了选项 i 这将使搜索不区分大小写。

查询如下:

db.collection.find({
  $or: [
    {
      title: {
        $regex: keyword,
        $options: "i"
      },
      
    },
    {
      shortDescriptipn: {
        $regex: keyword,
        $options: "i"
      },
      
    },
    {
      detailDescription: {
        $regex: keyword,
        $options: "i"
      },
      
    },
    {
      "category.title": {
        $regex: keyword,
        $options: "i"
      }, 
    },
  ],
})

您也可以在此处查看查询:https://mongoplayground.net/p/7zuhbaNTWJY

如果您有任何疑问,请在评论中告诉我。