0
Good afternoon, I need to know how to do it, using Mongoose, to filter a model from a foreign property. For example:
const Usuario = new Schema ({
nome: { type: String, required: true },
cargo: {
type: Schema.Types.ObjectId,
ref: "Cargo"
}
})
const Cargo = new Schema ({
nome: { type: String, required: true },
sigla: { type: String, required: true}
})
I am making the query as follows (consult users who have position with acronym CDC):
const consultarUsuarioPorCargo = async () => {
const usuarios = await Usuario.find()
.select('nome')
.populate({
path: 'cargo',
model: 'Cargo',
match: {'sigla': 'CDC'},
select: 'nome'
})
}
However, instead of bringing only users who hold the position with the acronym CDC, it brings all users and those who do not give match, it fills the position property with null.
Does anyone know how to make this filter?
Voce tried to pass the
CDC
how regex? and another thing, if that was the problem, doing an array filtering by JS itself would not solve the problem?– Cmte Cardeal
Doing filtering on JS itself would hurt performance. There are models with thousands of documents.. Mongo would return all these thousands of documents and then filter the application.
– Diego Sabino