NODEJS mongodb how to put variable inside like query

Viewed 3031

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.

1 Answers

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

Related