Jeremy
Jeremy

Reputation: 1675

Mongoose Find subdocument in array

I have the following data in Robo3t Mongo collection With this model:

const eleccionSchema = new mongoose.Schema({
    e: [{
        id: {
            type: String,
            required: true
        },
        l:[...]
    }],
    eleccion: {
        type: Number,
        required: true,
        ref: 'Corte'
    }
})
//? Create the model
const Eleccion = mongoose.model('Eleccion', eleccionSchema)

Right now I'm trying to fetch some data based on e.id like this

const eleccion = await Eleccion.findOne({'e.id':'A'})

But it's actually returning the whole array instead of just one output

Upvotes: 0

Views: 45

Answers (1)

Jeremy
Jeremy

Reputation: 1675

Fixed it with a projection: https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/

const eleccion = await Eleccion.findOne({}, {
 'e':
   { $elemMatch: { id: 'A' } }
})

Upvotes: 1

Related Questions