Within my function for constructing a search filter, there is the following logic:
const filter = {
$and: [
req.query.category !== "" ? { category: req.query.category } : {},
req.query.subCategory !== "" ? { tags: req.query.subCategory } : {},
req.query.contentType !== ""
? {
contentType: req.query.contentType,
}
: {},
req.query.searchTerm !== ""
? ({
name: {
$regex: "(?i)" + req.query.searchTerm + "(?-i)",
$options: "i",
},
},
{
tags: {
$regex: "(?i)" + req.query.searchTerm + "(?-i)",
$options: "i",
},
},
{
description: {
$regex: "(?i)" + req.query.searchTerm + "(?-i)",
$options: "i",
},
})
: {},
],
};
After executing console.log(filter)
, the result consistently shows an array of objects with all empty properties except for the last one, which retains its structure. If I modify the order or remove certain properties like this:
{
description: {
$regex: "(?i)" + req.query.searchTerm + "(?-i)",
$options: "i",
},
},
{
tags: {
$regex: "(?i)" + req.query.searchTerm + "(?-i)",
$options: "i",
},
}
, the outcome remains consistent with only the last object retaining its data
{ '$and': [ {}, {}, {}, { tags: [Object] } ] }
.
What could be causing this pattern of empty objects in the array?