Mongoose find or multiple columns not working

Issue

If keyword maches in category.title then it is giving result otherwise it is not matching with any other fields. Can somebody tell me what is the issue here?
Also tried NewsModel.find().or(filters) without $or key, still not working.

  let filters = {};

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

  const response = await NewsModel.find(filters);

mongoose:6.3.0

Update: DB collection added

 {
        "_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
    }

If I am searching for Entertainment, I get result but if I am searching for Moon Knight, I get empty array.

Solution

You can use this code to make it work, also you have misspelled shortDescriptipn in the database.

What i did is, i used $or keyword with regex search so you dont need to write full string, if it contains that part of string, it will return the document and wont be a strict full match case, also i have added option i which will make the search case insensitive.

The query will be like:

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"
      }, 
    },
  ],
})

You can also check the query here : https://mongoplayground.net/p/7zuhbaNTWJY

Let me know, if you have any doubts in comments.

Answered By – Ashishssoni

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.