db2791 db2791 - 1 month ago 12
Node.js Question

Mongoose search query

I'm implementing a search through a Mongodb database using Mongoose. On the client side, I have:

var searchQuery = {
title: ($('#responseTitle').val()),
text: ($('#responseKeywords').val())
};

$.ajax({
type: "GET",
url: "../../api/threads",
data: searchQuery,
success: function(data){
prefetchedResponses = data;
loadResponseBrowser();
}
})


On the server-side, I have:

router.get('/', function(req, res, next) {
Response.find(req.query, function(err, foundResponses){
...


This works, but only returns matches with the exact fields. I want to implement a regex-type search. However, I can't decide whether to do it on the client or server-side. On the server side, it would involve iterating through each field of
req.query
and appending the necessary properties to enable for regex search. On the client side, it would be easier, by just constructing
title
and
text
with those properties pre-defined. However, doing it on the client-side seems wrong to me, since the backend could change at any time.

Is there a third alternative in Mongoose that would allow me to apply regex to all fields?

Answer

No third alternative, you have to define your regex in client side :

var searchQuery = {
        title: {$regex: ($('#responseTitle').val()),  $options: "i"}, 
        text: {$regex: ($('#responseKeywords').val()), $options: "i"}
    };

Or in server side

for(var i in req.query)
{
    req.query[i] =  {$regex: req.query[i], $options: "i"};
}
Response.find(req.query, ....