I like to to go find a user in mongoDb by looking for a user called value. The problem with:
username: \'peter\'
is that i dont find it if
router.route('/product/name/:name')
.get(function(req, res) {
var regex = new RegExp(req.params.name, "i")
, query = { description: regex };
Product.find(query, function(err, products) {
if (err) {
res.json(err);
}
res.json(products);
});
});
The following query will find the documents with required string case insensitively and with global occurrence also
var name = 'Peter';
db.User.find({name:{
$regex: new RegExp(name, "ig")
}
},function(err, doc) {
//Your code here...
});
collection.findOne({
username: /peter/i
}, function (err, user) {
assert(/peter/i.test(user.username))
})
Just complementing @PeterBechP 's answer.
Don't forget to scape the special chars. https://stackoverflow.com/a/6969486
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var name = 'Peter+with+special+chars';
model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
//Do your action here..
});
Here my code with expressJS:
router.route('/wordslike/:word')
.get(function(request, response) {
var word = request.params.word;
Word.find({'sentence' : new RegExp(word, 'i')}, function(err, words){
if (err) {response.send(err);}
response.json(words);
});
});
This is my solution for converting every value in a req.body to a mongoose LIKE param:
let superQ = {}
Object.entries({...req.body}).map((val, i, arr) => {
superQ[val[0]] = { '$regex': val[1], '$options': 'i' }
})
User.find(superQ)
.then(result => {
res.send(result)})
.catch(err => {
res.status(404).send({ msg: err }) })