首页 > 解决方案 > 如何在猫鼬上聚合填充字段

问题描述

我需要将机器(maquinas)聚合到我的 Schema Producto

let ProductoFinal = new Schema([{
            cliente:{
                type:Schema.Types.ObjectId,
                ref: 'cliente'
            },
            grupo:{
                type:Schema.Types.ObjectId,
                ref: 'grupo'
            },
            nombre :{
                type:String
            },
            materiales: {
                type:Array
            }
}]);
 
//This is my productos Schema and I populated the grupo

let GrupoSchema = new Schema([{

    nombre:{
        type:String,
        required:true
    },
    tipos:{
        type:Array,
        required:true
    }

}]);

我用相同的 ID 用 grupos 填充了 Schema productos

Producto.findById(id)
            .populate('grupo')
            .exec((err, productosDB)=>{

            if( err ){
                return res.status(400).json({
                    ok:false,
                    err
                });
            }


            res.json({
                producto:productosDB
            })
    })

grupo 的tipo 是一个数组,我想从这个聚合所有具有相同tipo 的maquinas,我需要一个名为equipo 的字段,但是当我在字段grupo 中聚合时,会出现错误并且无法显示它

let MaquinaSchema = new Schema([{

    nombre:{
        type:String,
        required:true
    },
    tipo:{
        type:String,
        required:true
    },
    colores:{
        type:Number
    },
    cph:{
        type:Number,
        required:true
    }

}]);

我试过这个但不起作用

    Producto.findById(id)
            .populate('grupo')
            // .aggregate([
            //     {
            //         $lookup:{
            //             from:'maquinas',
            //             let:{
            //                 funcionMaquinas:"$grupo.tipos"
            //             },
            //             pipeline:[
            //                 {
            //                     $match:{
            //                         $expr:{
            //                             $in:["$tipo","$$funcionMaquinas",]
            //                         }
            //                     },
            //                 }
            //             ],
            //             as:'equipo'
            //         }
            //     }
            // ])
            .exec((err, productosDB)=>{

            if( err ){
                return res.status(400).json({
                    ok:false,
                    err
                });
            }


            res.json({
                producto:productosDB
            })
    })

标签: javascriptmongodbaggregate

解决方案


推荐阅读