4

I need to put variable inside mongodb like query. This is my code

  query={username: /req.params.data/}
  Users.find(query,function(err,users){
    if(err){
      console.log(err);

    }
    else{
      console.log(users);
    }
  });

req.params.data is a variable.I need to look for user that contains it.

bzzzzzz
  • 88
  • 1
  • 12
  • Why are you passing a regular expression, then? – jonrsharpe Nov 05 '18 at 08:16
  • I'm newbie with nodejs. Im passing the data with ajax to the controller. And I need to find the user. – bzzzzzz Nov 05 '18 at 08:17
  • So what exactly is the *problem*? Do you see errors? Unexpected outputs? Note that you're not actually *using* the value of `req.params.data`; it's probably best not to throw in random syntax like slashes if you don't know what you're doing. – jonrsharpe Nov 05 '18 at 08:19
  • I know, I tried to put in random text and It worked ,than I tried to put it like this query={username: "/"+req.params.data+"/"} but it doesn't take it as a like query for some reason idk why. – bzzzzzz Nov 05 '18 at 08:22
  • 1
    You need to make an actual regex, not just a string that looks like one, but using the value. Try `new RegExp(req.params.data)`. – jonrsharpe Nov 05 '18 at 08:24
  • That worked thank you. :-) – bzzzzzz Nov 05 '18 at 08:28

1 Answers1

1

req.params.data is a variable and will contain the passed username from front end.

 var userName = req.params.data; 

 User.findOne({ 'username': userName })
     .then(function(user){...})
     .catch(function(err){console.log(err)});
});

Ok if you need to perform a like search then use RegExp.

User.find(username: new RegExp(req.params.data));

or the old way is

User.find(username: {$regex: "/^" + req.params.data + "/"});

Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42