I have the following Mongoose Schema –
JavaScript
x
8
1
const myTableSchema = new Schema({
2
Category: { type: String, required: false },
3
Tag: { type: String, required: false },
4
5
createdAt: { type: Date, 'default': Date.now },
6
updatedAt: { type: Date, 'default': Date.now },
7
});
8
Note that, both of them are String. I was trying to do a query like the following –
JavaScript
1
2
1
localhost:1971/api/myTable?Category[$like]=Javascript
2
I have rows with Javascript in Category column. But getting the following error-
JavaScript
1
9
1
{
2
"name": "GeneralError",
3
"message": "Can't use $like with String.",
4
"code": 500,
5
"className": "general-error",
6
"data": {},
7
"errors": {}
8
}
9
Advertisement
Answer
I know its been a while since this was discussed, but I’ve had a similar question and the code provided by @Daff helped me a lot, but it contains an error.
query[field].$like
is checked for presence, but then query[field].$search
is attached to the final query.
The correct code representation (if following the original question) should be:
JavaScript
1
13
13
1
exports.searchRegex = function () {
2
return function (hook) {
3
const query = hook.params.query;
4
for (let field in query) {
5
if(query[field].$like && field.indexOf('$') == -1) {
6
query[field] = { $regex: new RegExp(query[field].$like) }
7
}
8
}
9
hook.params.query = query
10
return hook
11
}
12
}
13