Search code examples
mongoosemongoose-populatemongoosastic

Mongoose deep populate with Mongoosastic


I have read many of the mongoose deep populate docs and articles, but I can't seem to get it to work in this case, but I have a feeling it is because when the data was stored, dealSchema was without an id. Thoughts?

Because of the goal here of using mongoosastic and indexing the information in elasticsearch, I'm passing in the populate params with plugin.

//mongoose version 4.8.0

var dealSchema = new Schema({
    deal: {type: Schema.ObjectId, ref: 'Deal'},
    discounts: [discountSchema]
}, {_id:false});


var offerSchema = new Schema({
    name: String,
    description: String,
    partner: {type: Schema.ObjectId, ref: 'Partner'},
    venues: [{type: Schema.ObjectId, ref: 'Venue'}],
    deals: [dealSchema],
    modified: Date,
    created: Date
});


//=================================================//
mongoose.connect('mongodb://127.0.0.1:27017/production');
offerSchema.plugin(mongoosastic, {
  hosts: [ 'http://127.0.0.1:9200' ],
    index: 'myIndex',
    type: 'offer',
    populate: [
        { path: 'partner', model: 'Partner', select: 'name' },
        { path: 'venues', model: 'Venue', select: 'name' },
        { path: 'deals.deal', model: 'Deal', select: 'name' }
    ]
});

///////// indexed data in ES ///////////
// 1. partners and venues are populated as expected, name only.
// 2. deals.deal is not populated as intended

{
  "_index": "myIndex",
  "_type": "offer",
  "_id": "568454a104439f0300a57e86",
  "_score": 2.1182644,
  "_source": {
    "name": "offer name",
    "description": "This is an offer.",
    "partner": {
      "_id": "566ddbf61e11f0030020fcc5",
      "name": "partner one"
    },
    "venues": [
      {
        "_id": "566df15d1e11f00300211c13",
        "name": "venue one"
      },
      {
        "_id": "566df2f1b6e09103003595a6",
        "name": "venue two"
      }
    ],
    "deals": [
      {
        "deal": "566df755b6e091030035cbed",
        "discounts": [
          {
            "amount": 0,
            "attribute": "566ddeff1e11f0030020fccf"
          },
          {
            "amount": 0,
            "attribute": "566ddef91e11f0030020fcce"
          }
        ]
      }
    ],
    "modified": "2016-05-31T23:04:55.476Z",
    "created": "2015-12-30T22:03:13.354Z"
  }
}

Solution

  • The code below works. I needed to remove my elasticsearch index before re-running.

    mongoose.connect('mongodb://127.0.0.1:27017/production');
        offerSchema.plugin(mongoosastic, {
          hosts: [ 'http://127.0.0.1:9200' ],
            index: 'myIndex',
            type: 'offer',
            populate: [
                { path: 'partner', model: 'Partner', select: 'name' },
                { path: 'venues', model: 'Venue', select: 'name' },
                { path: 'deals.deal', model: 'Deal', select: 'name' }
            ]
        });