Skip to content

Commit 0229ffd

Browse files
authored
Merge pull request #13763 from Automattic/vkarpov15/gh-13720
fix(document): correctly handle inclusive/exclusive projections when applying subdocument defaults
2 parents 0604133 + 44f3f0d commit 0229ffd

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

lib/schema/SubdocumentPath.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const geospatial = require('./operators/geospatial');
1717
const getConstructor = require('../helpers/discriminator/getConstructor');
1818
const handleIdOption = require('../helpers/schema/handleIdOption');
1919
const internalToObjectOptions = require('../options').internalToObjectOptions;
20+
const isExclusive = require('../helpers/projection/isExclusive');
2021
const utils = require('../utils');
2122

2223
let Subdocument;
@@ -173,7 +174,8 @@ SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) {
173174
subdoc = new Constructor(void 0, selected, doc, false, { defaults: false });
174175
delete subdoc.$__.defaults;
175176
subdoc.$init(val);
176-
applyDefaults(subdoc, selected);
177+
const exclude = isExclusive(selected);
178+
applyDefaults(subdoc, selected, exclude);
177179
} else {
178180
options = Object.assign({}, options, { priorDoc: priorVal });
179181
if (Object.keys(val).length === 0) {

test/document.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12296,6 +12296,22 @@ describe('document', function() {
1229612296
assert.strictEqual(test.polluted, undefined);
1229712297
assert.strictEqual(Object.prototype.polluted, undefined);
1229812298
});
12299+
12300+
it('sets defaults on subdocs with subdoc projection (gh-13720)', async function() {
12301+
const subSchema = new mongoose.Schema({
12302+
propertyA: { type: String, default: 'A' },
12303+
propertyB: { type: String, default: 'B' }
12304+
});
12305+
const userSchema = new mongoose.Schema({
12306+
name: String,
12307+
sub: { type: subSchema, default: () => ({}) }
12308+
});
12309+
const User = db.model('User', userSchema);
12310+
await User.insertMany([{ name: 'user' }]);
12311+
await User.updateMany({}, { $unset: { 'sub.propertyA': '' } });
12312+
const nestedProjectionDoc = await User.findOne({}, { name: 1, 'sub.propertyA': 1, 'sub.propertyB': 1 });
12313+
assert.strictEqual(nestedProjectionDoc.sub.propertyA, 'A');
12314+
});
1229912315
});
1230012316

1230112317
describe('Check if instance function that is supplied in schema option is availabe', function() {

types/augmentations.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,4 @@ declare module 'bson' {
66
/** Mongoose automatically adds a conveniency "_id" getter on the base ObjectId class */
77
_id: this;
88
}
9-
}
9+
}

0 commit comments

Comments
 (0)