I'm trying to make a query in mongoose and I can not think of how to put it together. In SQL it would be something like this:
SELECT * FROM MATERIAS
WHERE
activo = true AND
nivel = $nivel_id AND
(alldisc = true OR disciplina = $disciplina_id)
where $nivel_id
and $disciplina_id
variables.
This same thing I'm writing in nodejs and mongoose and I can not think of a good way to do it.
What I have done so far is:
function getMateriasFilter(req, res) {
var query = Materia.find({'active': true});
if (req.query.nivel) query.where('nivel', req.query.nivel);
if (req.query.disciplina) query.where('disciplina', req.query.disciplina).or('alldisc', true);
query
.populate('nivel')
.populate('periodo')
.populate('disciplina')
.exec(function(err, result) {
if (err) res.send(err);
res.json(result);
});
}
The line with the discipline ifif complicates me. That condition would be that if the discipline filter exists, I have to bring the one that matches the discipline or those that have the alldisc field in true.
Thank you very much already.