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? Commented 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. Commented 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. Commented 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. Commented 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). Commented Nov 5, 2018 at 8:24

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Okay, I get this but I need to get it inside like query.
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).
@bzzzzzz updated answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.