简体   繁体   中英

How get all data if field in query string is empty Node and Sequelize with Postgres

i'm studing Sequelize with Node, and i have a question..

I have the follow URL with params:

http://localhost:9000/api/get/Joao/ ""

The first parameter is name and the second is manager , respectively Joao and "" (i'm considering like empty)..

What i want is: If the second parameter is empty i want to get all data that has the name Joao..

Already put undefined, null in the code of the Sequelize but not working..

Someone could help me, please?

My code of Sequelize :

 getCubikMembers(req, res) { return Cubik .findAll({ where: { name: req.params.name, manager: null // what i put here to happen what i want? } }) .then(success => res.status(201).send(success)) .catch(err => res.status(err).send(err)) } 

My api:

 app.get('/api/get/:name/:manager',CubikersController.getCubikMembers); 

You can use or statement. I think possible solution would be like below. I have not tested the code.

 getCubikMembers(req, res) { const manager = req.params.manager; return Cubik .findAll({ where: { [Op.or]: [ {manager: manager ? manager : null }, {name: req.params.name } ] } }) .then(success => res.status(201).send(success)) .catch(err => res.status(err).send(err)) } 

Here is the docs for operators in sequelizejs.

http://docs.sequelizejs.com/manual/tutorial/models-usage.html#complex-filtering-or-not-queries

i got to do, but i have that to change the "" to undefined , i dont know but the value empty is different in Sequelize..

My code was:

 where: { name: req.params.name === 'undefined' ? { [Op.ne]: 'undefined' } : req.params.name, manager: req.params.manager === 'undefined' ? { [Op.ne]: 'undefined' } : req.params.manager }, 

Like this if some field is undefined it is ignored in the filter..

I hope to have helped someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM