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 the username is "Peter", or "PeTER".. or something like that.
So i want to do like sql
SELECT * FROM users WHERE username LIKE 'peter'
Hope you guys get what im askin for?
Short: 'field LIKE value' in mongoose.js/mongodb
This question is related to
javascript
node.js
mongodb
find
mongoose
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);
});
});
mongoose doc for find. mongodb doc for regex.
var Person = mongoose.model('Person', yourSchema);
// find each person with a name contains 'Ghost'
Person.findOne({ "name" : { $regex: /Ghost/, $options: 'i' } },
function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation);
});
Note the first argument we pass to mongoose.findOne
function: { "name" : { $regex: /Ghost/, $options: 'i' } }
, "name"
is the field of the document you are searching, "Ghost"
is the regular expression, "i"
is for case insensitive match. Hope this will help you.
collection.findOne({
username: /peter/i
}, function (err, user) {
assert(/peter/i.test(user.username))
})
if I want to query all record at some condition,I can use this:
if (userId == 'admin')
userId = {'$regex': '.*.*'};
User.where('status', 1).where('creator', userId);
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...
});
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 }) })
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);
});
});
You should use a regex for that.
db.users.find({name: /peter/i});
Be wary, though, that this query doesn't use index.
I had problems with this recently, i use this code and work fine for me.
var data = 'Peter';
db.User.find({'name' : new RegExp(data, 'i')}, function(err, docs){
cb(docs);
});
Use directly /Peter/i
work, but i use '/'+data+'/i'
and not work for me.
This is what I'm using.
module.exports.getBookByName = function(name,callback){
var query = {
name: {$regex : name}
}
User.find(query,callback);
}
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..
});
For dynamic search, you can follow like this also,
const { keyword, skip, limit, sort } = pagination(params);
const search = keyword
? {
title: {
$regex: new RegExp(keyword, 'i')
}
}
: {};
Model.find(search)
.sort(sort)
.skip(skip)
.limit(limit);
db.users.find( { 'username' : { '$regex' : req.body.keyWord, '$options' : 'i' } } )
Source: Stackoverflow.com