首页 > 解决方案 > 如何使用 Autopopulate Mongoose Mongodb 选择要检索的字段?

问题描述

我正在使用插件 mongoose-autopopulate 但我不知道如何指定要从填充集合中检索的字段。

这是我的架构...

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',
        autopopulate: true
    }]
})

所以我想选择儿童填充集合中的字段,因为 productos 字段带来了很多文档。

我怎么会有这样的输出......

{
    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;
}

标签: mongodbmongoose

解决方案


我找到了解决方案。

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

    }],

autopopulate 接受选项,然后您可以选择或取消选择要排除或添加的字段。


推荐阅读