0

Hi I am trying to find a value that is like a variable in a mongodb database. I get no results though and I am not sure what I am doing wrong. If my username is just d then I should see some users with d in their name but I don't.

//Find a user
router.get('/findUser/:username', function (req, res) {
  var user = req.params.username;
  var db = req.db;
  var collection = db.get('userlist');
  collection.find({'username':  '/^' + user + '/' }, {}, function (e, docs) {
    res.json(docs);
  });
});
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
maximdj
  • 315
  • 1
  • 12

3 Answers3

1

With /^d/ (no quotes) you can create a RegExp in JavaScript. In your example you used quotes and hence created a plain string instead of a RegExp. If you want to use a variable in your regular expression, you have to use the RegExp constructor:

var userRegex = new RegExp('^' + user);
collection.find({'username':  userRegex}, function (e, docs) {
    res.json(docs);
  });

Also see mongo js docs

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
  • As @dnickless pointed out, you can also just leave out the caret, if you want a "contains". If you need a case-insensitive search, add the `i` flag: `new RegExp(user, 'i');` – Kim Kern Aug 03 '17 at 21:49
1

The caret sign ^ means: beginning of the text. If you get rid of that, you have a proper "contains" query if that is what you expect.

Also, you might want to add an 'i' after the second slash in order to make the query case-insensitive:

Mind you, I don't think that the '/' based syntax works in conjunction with a variable (user in your case). So try this one instead:

collection.find({'username':{'$regex' : user, '$options' : 'i'}})

Be sure to check out this SO answer, too:

https://stackoverflow.com/a/33971033/6440033

dnickless
  • 10,733
  • 1
  • 19
  • 34
0

I used this and it seems to work:

router.get('/findUser/:username', function (req, res) {


var user = req.params.username;
var reg = new RegExp(user, 'i')
var db = req.db;
var collection = db.get('userlist');
collection.find({ 'username': { $regex: reg }}, function (e, docs) {
res.json(docs);
});

});

maximdj
  • 315
  • 1
  • 12
  • You don't need to do both. Either use the $regex syntax with the options parameter or create the regular expression and use it like `{'username': reg}`. See the link to the docs I posted under "Regular expressions in queries" – Kim Kern Aug 03 '17 at 22:02