Js: 通过用户名 LIKE 值查找用户

我喜欢通过查找名为 value 的用户来查找 mongoDb 中的用户。 问题在于:

username: 'peter'

是我没有找到它,如果用户名是“彼得”,或“彼得”... 或类似的东西。

所以我想像 sql 一样

SELECT * FROM users WHERE username LIKE 'peter'

希望你们能得到我想要的?

Short: mongoose.js/mongodb 中的‘ field LIKE value’

146069 次浏览

You should use a regex for that.

db.users.find({name: /peter/i});

Be wary, though, that this query doesn't use index.

collection.findOne({
username: /peter/i
}, function (err, user) {
assert(/peter/i.test(user.username))
})

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.

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
//Do your action here..
});
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);
});


});

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

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.

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 what I'm using.

module.exports.getBookByName = function(name,callback){
var query = {
name: {$regex : name}
}
User.find(query,callback);
}
db.users.find( { 'username' : { '$regex' : req.body.keyWord, '$options' : 'i' } } )

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

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

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);
var name = 'Peter';


model.findOne({
name: {
$regex: name,
$options: 'i'
},
function(err, doc) {
//your logic
});

for more information you can refer this link https://www.mongodb.com/docs/manual/reference/operator/query/regex/