Search username in a Query of the Mongoose-paginate

Asked

Viewed 173 times

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!

1 answer

0

You can instantiate an object of the Regexp class to be able to concatenate strings within it. Something like: const searchRegex = new RegExp('^' + search). Then just use the constant searchRegex the same way you used the literal regex in your example.

  • Funcionoou! Thank you very much :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.