Mongoose 'or' and 'like' node.js operators

I want to search for my page. So from frontEnd I got the search value from user input and I need search in my db with 3 lines limit. So i need sql query: SELECT * FROM PRODUCTS p WHERE p.title like '% user_value%' or p.sku like '% user_value%'

I am trying to do it like this:

router.get('/search', function(req, res, next) {
    var value = req.query.val;
    var query = Product.find({"title":  new RegExp('/' + value+'/')}).limit(3);

    query.exec(function(err, products) {
        if (!err) {
            // Method to construct the json result set
            var result =  JSON.stringify(products);
            log.info(products);

            res.send(result, {
                'Content-Type': 'application/json'
            }, 200);
        } else {
            res.send(JSON.stringify(err), {
                'Content-Type': 'application/json'
            }, 404);
        }
    });

      

But I always got empty results. It seems to me that the RegExp path is not valid.

Update1: The "like" operator is fixed like this:

Product.find({"title": new RegExp(".*" + value + ".*")}).limit(3);

      

But the problem "or p.sku like '%user_value%'"

still takes place

+3


source to share


2 answers


You need to pass modifiers as the second parameter in the constructor RegExp

.

var query = Product.find({"title": new RegExp(".*" + value.replace(/(\W)/g, "\\$1") + ".*", "i")}).limit(3);

      



Example:

> var value = 'SNR-SFP+W73-60'
> console.log(new RegExp(".*" + value.replace(/(\W)/g, "\\$1") + ".*", "i"))
/.*SNR\-SFP\+W73\-60.*/i

      

+3


source


In your RegExp object, you should do this:

new RegExp(value)

      

instead of this:



new RegExp('/' + value + '/')

      

Follow this link: RegExp

0


source







All Articles