LIKE in Mongoose
Since it is the only way in MongoDB (except using a text index which has some constraints), it is the best way.
I think you can only achieve the same behaviour with javascript. Something like below would do the conversion of LIKE
to RegExp
.
(Didn't test, so might not work as it is.)
function createLikeRegex(query) { query = query .replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') .replace(/(^|[^\\\])%#/g, '\\$&'); if (! query.startsWith('%')) { query = '^' + query; } if (! query.endsWith('%')) { query += '$'; } return new RegExp(query, 'i');}