0

This is my Schema, I have a CampaignStat Object which has a nested Product Schema, but at the same time Product is another model.

const ProductsSchema = new Schema({
_id: {
  type: mongoose.Schema.ObjectId,
  ref: 'Product'
},
clickedAt: Date,
deviceInfo: {
  type: Schema.Types.Mixed
}}, { _id: false })

const CampaignStatSchema = new Schema({
campaign: {
  type: mongoose.Schema.ObjectId,
  ref: 'Campaign'
},
subscriber: {
  type: mongoose.Schema.ObjectId,
  ref: 'Subscriber'
},
openedAt: Date,
products: [ProductsSchema]
}, {
 timestamps: { createdAt: true, updatedAt: false }
})

An this is how is being stored in MongoDB

"_id" : ObjectId("5f18d01ecab4eb6175cc0f83"),
"subscriber" : ObjectId("5ed6890da2c99843280a0058"),
"campaign" : ObjectId("5ed937829ff2a1f99de55150"),
"products" : [ 
    {
        "_id" : ObjectId("5f160ca2014be4e159f32fcd")
    }, 
    {
        "_id" : ObjectId("5f160ca2014be4e159f3302e")
    }, 
    {
        "_id" : ObjectId("5f160ca2014be4e159f33036")
    }, 
    {
        "_id" : ObjectId("5f160ca2014be4e159f3311a")
    }, 
    {
        "_id" : ObjectId("5f160ca2014be4e159f33159")
    }
],
"createdAt" : ISODate("2020-07-22T23:47:42.228Z"),
"__v" : 0

I need to populate Products, I'm doing this but I cannot get the Product collection attributes

const CampaignStats = await this.find({ campaign: "5ed937829ff2a1f99de55150" })
      .populate('subscriber')
      .populate({
        path: 'products',
        model: 'Product'
      })
utiq
  • 1,342
  • 2
  • 17
  • 33

1 Answers1

0

In case somebody gets into the same problem, I changed this (_id for product):

const ProductsSchema = new Schema({
product: {
  type: mongoose.Schema.ObjectId,
  ref: 'Product'
},
clickedAt: Date,
deviceInfo: {
  type: Schema.Types.Mixed
}}, { _id: false })

And my query is like this:

this.find(query)
  .populate({ 
     path: 'products',
     populate: {
       path: 'product',
       model: 'Product'
     } 
  })
utiq
  • 1,342
  • 2
  • 17
  • 33