mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
222 stars 36 forks source link

Select fields from populated documents #75

Closed calldeludo closed 4 years ago

calldeludo commented 4 years ago

Hello, i am trying to control the fields that are populated but i don't know how to do it, i searched in the solved issued but could not find any solution.

Here is my Schema:

const categoriaSchema = new Schema({
    data: { type: String },
    label: { type: String },
    children: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'categorias',
        autopopulate: true
    }],
    father: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'categorias',
        autopopulate: true
    },
    eventos: { type: Boolean },
    tienda: { type: Boolean },
    productos: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'productos',
    }]
})

I would like to remove Productos from the children autopopulate.... example of output...

{
    data: "Electronic",
    label: "Electronic",
    children: [
        { 
        data: "Mobiles",
        label: "Mobiles",
        children: [
            {   
            data: "Samsung",
            label: "Samsung",
            children: [],
            eventos: true;
            tienda: true;
            }
        ],
        eventos: true;
        tienda: true;
        }
    ],
    eventos: true;
    tienda: true;
}

Any idea? Thank you in advance

calldeludo commented 4 years ago

i found the solution.

children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'categorias', autopopulate: { select: '-productos' },

}],

Autopopulate accepts options then you can select or unselect the fields that you want exclude