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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(document): ensure transform function passed to toObject() opt… #14600

Merged
merged 1 commit into from
May 17, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -3831,16 +3831,14 @@ Document.prototype.$toObject = function(options, json) {
// need the original options the user passed in, plus `_isNested` and
// `_parentOptions` for checking whether we need to depopulate.
const cloneOptions = {
...options,
_isNested: true,
json: json,
minimize: _minimize,
flattenMaps: flattenMaps,
flattenObjectIds: flattenObjectIds,
_seen: (options && options._seen) || new Map(),
_calledWithOptions: options._calledWithOptions,
virtuals: options.virtuals,
getters: options.getters,
depopulate: options.depopulate
_calledWithOptions: options._calledWithOptions
};

const depopulate = options.depopulate ||
Expand Down
28 changes: 28 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,34 @@ describe('document', function() {
docs.toObject({ transform: true });
});

it('propagates toObject transform function to all subdocuments (gh-14589)', async function() {
const schema = new mongoose.Schema({
name: String,
docArr: [{ name: String }],
subdoc: new mongoose.Schema({ name: String })
});
const TestModel = db.model('Test', schema);

const doc = new TestModel({
name: 'test',
docArr: [{ name: 'test' }],
subdoc: { name: 'test' }
});

// pass the transform as an inline option. Deletes `_id` property
// from both the top-level document and the subdocument.
const obj = doc.toObject({ transform: deleteId });

assert.equal(obj._id, undefined);
assert.equal(obj.subdoc._id, undefined);
assert.equal(obj.docArr[0]._id, undefined);

function deleteId(doc, ret) {
delete ret._id;
return ret;
}
});

it('disabling aliases in toObject options (gh-7548)', function() {
const schema = new mongoose.Schema({
name: {
Expand Down