Mongoose - Filter by foreign ownership

Asked

Viewed 21 times

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?

  • 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.

No answers

Browser other questions tagged

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