Reputation: 1
How can I search mongodb by username ? I have database with unique usernames, but I want when I enter search query to get a list of all usernames that contains similar characters. For example if I search for 'name' that I get 'name1' , 'name_1', 'name2' etc. Here is my code:
router.post('/search', (req, res, next) => {
User.find({username: req.body.username})
.then(user => {
if(user){
res.json({user});
}else {
return res.json({success: false, message: 'User not found'});
}
});
Upvotes: 0
Views: 54
Reputation: 19569
A few ways:
Regex, as mentioned:
User.find({ username: /name/i });
$where:
User.find({ $where: { "username.toLowerCase().indexOf(name.toLowerCase()) > -1" }});
Mind that this is both very slow, especially if you have a lot of users, as those operations won't use indexes. You could get a bit of help there if you use regex with a prefix (start-of-word), e.g.
User.find({ username: /^name/ });
Upvotes: 0
Reputation: 749
You can use Regular expressions in queries, thats means that queried field values can also be matched with regular a expression. For example: { username: /^name/}
In this case will search all usernames that starts with name, but you can play with teh regular expression.
For more information: https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html
Upvotes: 1