How do I put more than one filter in my search for a get?

Asked

Viewed 333 times

0

I am using mongodb and Node. In the code below I am only searching for an 8 digit code, but I wanted to put also a search by name, as I do?

exports.getByCode = (req, res, next) => {
    Roles
        .findOne({
            codigo: req.params.codigo,
            active: true
        }, '_id title price address date hora createBy minuto alcohol tags')
        .then(data => {
            res.status(200).send({
                message: 'Listagem de roles especificos por user feita com sucesso',
                statusCode: 200,
                body: data,
            })
        }).catch(e => {
            res.status(400).send({
                statusCode: 400,
                message: 'Falha ao cadastrar o role',
                error: e
            });
        });
},
  • Voce tried to use query? If using express, Voce can use req.query to bring more than one parameter through the url. See here => https://expressjs.com/pt-br/api.html#req.query

  • does something like this before to see if you’re picking up the const {code} = req.params.code and then run console.log(code) is a little weird this code parameter, edit your question and put the route and schema referring to the Rules.

1 answer

0

Good evening, when making an api request with more than one filter a good practice is to use queryParams instead of pathParams as used in the example.

This way you can have as many filters as needed in the req Object.

Ex of a possible solution, assuming http://sua_url/end_point?codigo=12345789&nome=Jhon:

exports.getByCode = (req, res, next) => {
    const { codigo, nome } = req.query
    Roles
        .findOne({
            codigo, 
            nome,
            active: true
        }, '_id title price address date hora createBy minuto alcohol tags')
        .then(data => {
            res.status(200).send({
                message: 'Listagem de roles especificos por user feita com sucesso',
                statusCode: 200,
                body: data,
            })
        }).catch(e => {
            res.status(400).send({
                statusCode: 400,
                message: 'Falha ao cadastrar o role',
                error: e
            });
        });
}

Browser other questions tagged

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