Reputation: 990
I am trying to build a mongoose aggregate query dynamically based on the content of an array variable passed in a POST api call as shown below, yet I am always receiving error "$or/$and/$nor entries need to be full objects" so was wondering if anyone can review my code below please let me know what I might be missing / doing wrong?
static search (searchData) {
let { searchTerm, filterBy } = searchData;
searchTerm = Utils.escapeRegexSpecialCharacters(searchTerm);
let filterByElementsLength = filterBy.length;
if(filterByElementsLength === 0) {
query.push({
$match: { 'bookTitle': new RegExp(searchTerm, 'i') },
});
}else if (filterByElementsLength > 0) {
query.push({
$match: { $and: [
{ 'bookTitle': new RegExp(searchTerm, 'i') },
filterBy
] }
});
}
}
Taking in consideration that filterBy content is posted as JSON (Application/json) using Postman with the following content example:
"filterBy": [{"author": "Michael White" }, { "Price_Less_Than": "100" }],
Thanks for your support
Upvotes: 0
Views: 391
Reputation: 990
Found a solution, posting it here below:
let matchQry = [];
matchQry.push({ 'bookTitle': new RegExp(searchTerm, 'i') });
for(let i = 0; i < filterByElementsLength; i++) {
matchQry.push(filterBy[i]);
}
query.push({
$match: { $and: matchQry }
});
If anyone think there could be a better solution, please let me know. Thanks for your support
Upvotes: 2