1
I am trying to do a user search field and for that I will receive via query param a variable search
, which will contain the string search (in this case, the name (or part of a name) of one or more users).
If I were doing this query with a bank SQL in a language such as Java, would be something like:
String sql = "SELECT * FROM User WHERE name LIKE '%" + search + "'";
Then put this variable sql
within a preparedStatement
and executes the query.
However, studying Mongoose-paginate, in Nodejs, I’m not able to do a query of this type, because I can’t get the variable I’m receiving in the URL and pass it to the Mongoose query. My method findByName
is like this:
async findByName(req, res){
let { search, page=1, limit=10 } = req.query;
page = parseInt(page);
limit = parseInt(limit);
const users = await User.paginate({ name: /^L/ }, {page, limit});
return res.json(users);
}
The way the code is above, all users that have the name starting with "L" will be returned. But I want to replace the snippet const users = await User.paginate({ name: /^L/ }, {page, limit});
for something like const users = await User.paginate({ name: /^search/ }, {page, limit});
, that is to say, pass the variable search
, which is coming in the URL, as a parameter for the database search.
I’ve tried to do something like:
async findByName(req, res){
let { search, page=1, limit=10 } = req.query;
page = parseInt(page);
limit = parseInt(limit);
const consulta = "/^"+search+"/";
const users = await User.paginate({ name: consulta }, {page, limit});
return res.json(users);
}
I also tried to replace it with User.paginate({ name: /^${search}/}, {page, limit});
, or use the operator
" ` " Javascript, to access the variable with the notation ${search}
, but I was unsuccessful.
Does anyone have any idea how this should be done? Thank you!
Funcionoou! Thank you very much :D
– João Bonsegno