mongoose'或'和'喜欢'运营商node.js

我想实现search我的网页。 所以从前端我得到了来自用户的inputsearch值,我需要在我的数据库search3行限制。 所以我需要这样的SQL查询:SELECT * FROM PRODUCTS p WHERE p.title like'%user_value%'或p.sku like'%user_value%'

我试图这样做:

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); } }); 

但是我总是得到空的结果。 在我看来,RegExppath无效。

UPDATE1:像这样修改 'like'操作符:

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

但是"or p.sku like '%user_value%'"问题仍然存在

您需要在RegExp构造函数中传递修饰符作为第二个参数。

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

例:

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

在你的RegExp对象中,你应该这样做:

 new RegExp(value) 

而不是这个:

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

请参阅此链接: RegExp