Skip to content

Commit

Permalink
Merge pull request #13758 from Automattic/vkarpov15/mongoose-autopopu…
Browse files Browse the repository at this point in the history
…late-96

fix(query+populate): add `refPath` to projection by default, unless explicitly excluded
  • Loading branch information
vkarpov15 authored Aug 22, 2023
2 parents 5fdb89c + 2f101d0 commit b0258e1
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/helpers/query/selectPopulatedFields.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,25 @@ module.exports = function selectPopulatedFields(fields, userProvidedFields, popu
} else if (userProvidedFields[path] === 0) {
delete fields[path];
}

const refPath = populateOptions[path]?.refPath;
if (typeof refPath === 'string') {
if (!isPathInFields(userProvidedFields, refPath)) {
fields[refPath] = 1;
} else if (userProvidedFields[refPath] === 0) {
delete fields[refPath];
}
}
}
} else if (isExclusive(fields)) {
for (const path of paths) {
if (userProvidedFields[path] == null) {
delete fields[path];
}
const refPath = populateOptions[path]?.refPath;
if (typeof refPath === 'string' && userProvidedFields[refPath] == null) {
delete fields[refPath];
}
}
}
};
Expand Down
36 changes: 36 additions & 0 deletions test/helpers/query.selectPopulatedFields.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const assert = require('assert');
const selectPopulatedFields = require('../../lib/helpers/query/selectPopulatedFields');

describe('selectPopulatedFields', function() {
it('selects refPath', function() {
const fields = { name: 1 };
const userProvidedFields = { name: 1 };
const populateOptions = {
parent: {
refPath: 'parentModel'
}
};
selectPopulatedFields(fields, userProvidedFields, populateOptions);
assert.deepStrictEqual(fields, {
name: 1,
parent: 1,
parentModel: 1
});
});

it('adds refPath to projection if not deselected by user in exclusive projection', function() {
const fields = { name: 0, parentModel: 0 };
const userProvidedFields = { name: 0 };
const populateOptions = {
parent: {
refPath: 'parentModel'
}
};
selectPopulatedFields(fields, userProvidedFields, populateOptions);
assert.deepStrictEqual(fields, {
name: 0
});
});
});

0 comments on commit b0258e1

Please sign in to comment.