Skip to content

Commit

Permalink
Merge pull request #13408 from hasezoey/addModelNameToError
Browse files Browse the repository at this point in the history
fix(getModelMapForPopulate): mention model name in error
  • Loading branch information
vkarpov15 authored May 18, 2023
2 parents 23579f2 + 66c5530 commit 02fd721
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
3 changes: 1 addition & 2 deletions lib/helpers/populate/getModelsMapForPopulate.js
Original file line number Diff line number Diff line change
Expand Up @@ -389,8 +389,7 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
let foreignField = virtual.options.foreignField;

if (!localField || !foreignField) {
return new MongooseError('If you are populating a virtual, you must set the ' +
'localField and foreignField options');
return new MongooseError(`Cannot populate virtual \`${options.path}\` on model \`${model.modelName}\`, because options \`localField\` and / or \`foreignField\` are missing`);
}

if (typeof localField === 'function') {
Expand Down
41 changes: 41 additions & 0 deletions test/helpers/getModelsMapForPopulate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

const assert = require('assert');
const start = require('../common');
const util = require('../util');

const mongoose = start.mongoose;
const Schema = mongoose.Schema;

describe('getModelsMapForPopulate', function() {
let db;

beforeEach(() => db.deleteModel(/.*/));

before(function() {
db = start();
});

after(async function() {
await db.close();
});

afterEach(() => util.clearTestData(db));
afterEach(() => util.stopRemainingOps(db));

it('should error on missing options on populate', async function() {
const sch = new Schema({
test: mongoose.Schema.Types.ObjectId
}, {
virtuals: {
someVirtual: {}
}
});

const model = db.model('Test', sch);

const doc = await model.create({ test: new mongoose.Types.ObjectId() });

await assert.rejects(() => model.findById(doc._id).populate('someVirtual').exec(), /Cannot populate virtual `someVirtual` on model `Test`, because options `localField` and \/ or `foreignField` are missing/);
});
});

0 comments on commit 02fd721

Please # to comment.