Search code examples
mongodbmongoose

Problem with aggregate in mongoDB to populate


There are various pieces of information in the transaction model that are not required, for example, We don't know if the transaction is registered for dealer or delivery, and if it is for either, the other is empty

    dealer: {
  type: SchemaTypes.ObjectId,
  ref: 'Dealer',
  required: false,
},
delivery: {
  type: SchemaTypes.ObjectId,
  ref: 'Delivery',
  required: false,
},

When I use aggregate, only data that has both dealer value and delivery is returned

 const aggregate = [
{
  $lookup: {
    from: 'deliveries',
    localField: 'delivery',
    foreignField: '_id',
    as: 'delivery',
  },
},
 {
  $unwind:"$delivery",
  },
{
  $lookup: {
    from: 'dealers',
    localField: 'dealer',
    foreignField: '_id',
    as: 'dealer',
  },
},
{
  $unwind: '$dealer',
}]

so, no data is returned How can you do aggregate if there is a field in a document, it doesn't matter if it doesn't exist


Solution

  • you can $unwind with preserveNullAndEmptyArrays set to true so that the document won't get removed if there is an empty array to unwind. Here is a mongoplayground demo

    const aggregate = [
      {
        $lookup: {
          from: "deliveries",
          localField: "delivery",
          foreignField: "_id",
          as: "delivery",
          
        }
      },
      {
        $unwind: {
          path: "$delivery",
          preserveNullAndEmptyArrays: true
        }
      },
      {
        $lookup: {
          from: "dealers",
          localField: "dealer",
          foreignField: "_id",
          as: "dealer",
          
        }
      },
      {
        $unwind: {
          path: "$dealer",
          preserveNullAndEmptyArrays: true
        }
      }
    ]