buunguyen / mongoose-deep-populate

Mongoose plugin to enable deep population of nested models ⛺
MIT License
469 stars 44 forks source link

Cannot deep populate when there is a subdocument in a linked document #29

Closed cthiebot closed 9 years ago

cthiebot commented 9 years ago

Hi,

I think there is an issue with the following scenario:

First schema:

var schemaA = new mongoose.Schema({b: {type: mongoose.Schema.Types.ObjectId, ref: 'B'}});

schemaA.plugin(deepPopulate);

var ModelA = mongoose.model('A', schema);

Second schema:

var schemaB = new mongoose.Schema({subField: {c: {type: mongoose.Schema.Types.ObjectId, ref: 'C'}}});

var ModelB = mongoose.model('B', schema);

Third schema:

var schemaC = new mongoose.Schema({
// whatever...
});

var ModelC = mongoose.model('C', schema);

I found a working solution: In the function "getModelFromPath", there is an issue with candidateModel.

When deep populating b.subField.c, there are few iterations:

  1. getModelFromPath('b') -> There is a schema B, it returns ModelB
  2. getModelFromPath('b.subField') -> There is no schema but it returns anyways schema B. This is because candidateModel is not reset to null
  3. getModelFromPath('b.subField.c') -> it returns an error because actually the lib tries to populate subField (with model B) with field c

My solution : reset to null candidateModel when no schema is found:

function getModelFromPath(db, model, path) {
  ...
  // no schema, possibly a subdocument, continues to find out
  if (!schemaPath) {
    candidateModel = null
    return
  }
  ...
}

Tests pass again.

What do you think about this?

buunguyen commented 9 years ago

Fixed in 2.0.2. Thank you for the detailed bug report.

mathpere commented 9 years ago

Thank you!