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.

6
  • Why are you passing a regular expression, then?
    – jonrsharpe
    Nov 5 2018 at 8:16
  • I'm newbie with nodejs. Im passing the data with ajax to the controller. And I need to find the user.
    – bzzzzzz
    Nov 5 2018 at 8: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 5 2018 at 8: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 5 2018 at 8: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 5 2018 at 8:24
2

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 + "/"});

3
  • Okay, I get this but I need to get it inside like query.
    – bzzzzzz
    Nov 5 2018 at 8:25
  • This doesn't solve the OP's problem; that's still not a like query. Also it's helpful to explain the changes you've made (or just stick with the callback they were already using).
    – jonrsharpe
    Nov 5 2018 at 8:25
  • @bzzzzzz updated answer Nov 5 2018 at 8:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.