Marcus Declementi
Marcus Declementi

Reputation: 19

NodeJS - Mongoose Populate Nested Items

I am trying to populate a GET request.

This my model/schema:

const turnosSchema = mongoose.Schema({
    turno: { type: Number, required: true},
    nombre: { type: String, required: true},
    hora_inicio: { type: String, required: true},
    hora_fin: { type: String, required: true},
    menus: { type: Array, required: true},
    cod_vestir: { type: mongoose.Schema.Types.ObjectId, ref: 'cod_vestir', required: true},**//This is the item I want to populate with another collection called "codsvestirs"**
})

const LandingAyBSchema = mongoose.Schema({
    titulo: { type: String, required: true},
    especialidad: { type: String, required: true},
    descripcion: { type: String, required: true},
    observaciones: { type: String, required: true},
    turnos: [turnosSchema],**//This is an array with a "turnosSchema"**
    orden: { type: Number, required: true},
    activo: { type: Number, required: true},
    imagen: {type: String, required: true},
    lang: { type: String, required: true, maxLength: 2},
})

Heres is a pic of the data hierarchy.

enter image description here

Here is the code I have so far. It doesn't have the actual populate code cause I have not been able to make it work. I've tried the solution from this thread which I think better suits my scenario but it didn't work Populate nested array in mongoose

exports.getAllLandingAyB = async (req, res, next) => {

    const query_result = await LandingAyB.find({activo: 1}).sort({orden: 1});
    if (!query_result) {
        res.status(500).json({success: false})
    }
    res.status(200).json({
        success: true,
        cuantosLandings: query_result.length,
        data: query_result
    });

}

Upvotes: 0

Views: 42

Answers (1)

Fernando Jaimes
Fernando Jaimes

Reputation: 76

You need to set the type as a mongoId and then refer to the selected collection. For example on the turnos property

turnos: [{ type: Schema.Types.ObjectId, ref: 'Turnos' }] 

I'm asumming the Turnos is the name of the collection, and the query shoud look like this

 const query_result = await LandingAyB.find({activo: 1})
                                      .populate('turnos')
                                      .sort({orden: 1});.

you can find a good example on the populate documentation

Upvotes: 1

Related Questions