代码之家  ›  专栏  ›  技术社区  ›  utiq

Mongoose中的填充嵌套模式

  •  0
  • utiq  · 技术社区  · 6 年前

    这是我的模式,我有一个活动统计对象,它有一个嵌套的产品模式,但同时产品是另一个模型。

    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 }
    })
    

    这就是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
    

    我需要填充产品,我正在这样做,但我无法获得产品集合属性

    const CampaignStats = await this.find({ campaign: "5ed937829ff2a1f99de55150" })
          .populate('subscriber')
          .populate({
            path: 'products',
            model: 'Product'
          })
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   utiq    6 年前

    如果有人遇到同样的问题,我更改了这个(_idfor product):

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

    我的问题是:

    this.find(query)
      .populate({ 
         path: 'products',
         populate: {
           path: 'product',
           model: 'Product'
         } 
      })
    
    推荐文章