Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(populate): handle ref() functions that return a model instance #14343

Merged
merged 1 commit into from Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/helpers/populate/getModelsMapForPopulate.js
Expand Up @@ -494,7 +494,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re

let k = modelNames.length;
while (k--) {
const modelName = modelNames[k];
let modelName = modelNames[k];
if (modelName == null) {
continue;
}
Expand All @@ -504,6 +504,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
Model = options.model;
} else if (modelName[modelSymbol]) {
Model = modelName;
modelName = Model.modelName;
} else {
try {
Model = _getModelFromConn(connection, modelName);
Expand Down
46 changes: 46 additions & 0 deletions test/model.populate.test.js
Expand Up @@ -10922,4 +10922,50 @@ describe('model: populate:', function() {
assert.equal(personFromDb.userType, 'User');
assert.equal(personFromDb.userId.toHexString(), user._id.toHexString());
});

it('handles ref() function that returns a model (gh-14249)', async function() {
const aSchema = new Schema({
name: String
});

const bSchema = new Schema({
name: String
});

const CategoryAModel = db.model('Test', aSchema);
const CategoryBModel = db.model('Test1', bSchema);

const testSchema = new Schema({
category: String,
subdoc: {
type: Schema.Types.ObjectId,
ref: function() {
return this.category === 'catA' ? CategoryAModel : CategoryBModel;
}
}
});

const parentSchema = new Schema({
name: String,
children: [testSchema]
});
const Parent = db.model('Parent', parentSchema);

const A = await CategoryAModel.create({
name: 'A'
});
const B = await CategoryBModel.create({
name: 'B'
});

const doc = await Parent.create({
name: 'Parent',
children: [{ category: 'catA', subdoc: A._id }, { category: 'catB', subdoc: B._id }]
});

const res = await Parent.findById(doc._id).populate('children.subdoc');
assert.equal(res.children.length, 2);
assert.equal(res.children[0].subdoc.name, 'A');
assert.equal(res.children[1].subdoc.name, 'B');
});
});