Skip to content

Commit 40358bb

Browse files
committed
fix: avoid applying defaults on map embedded paths
Fix #15196
1 parent 6107403 commit 40358bb

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/helpers/document/applyDefaults.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ module.exports = function applyDefaults(doc, fields, exclude, hasIncludedChildre
1919
const type = doc.$__schema.paths[p];
2020
const path = type.splitPath();
2121
const len = path.length;
22+
if (path[len - 1] === '$*') {
23+
continue;
24+
}
2225
let included = false;
2326
let doc_ = doc._doc;
2427
for (let j = 0; j < len; ++j) {

test/types.map.test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1150,4 +1150,36 @@ describe('Map', function() {
11501150
const doc = await CarModel.findById(car._id);
11511151
assert.deepStrictEqual(doc.owners.get('abc').toObject(), [{ name: 'Bill' }]);
11521152
});
1153+
1154+
it('handles loading and modifying map of document arrays (gh-15196)', async function() {
1155+
const schema = new Schema({
1156+
name: { type: String, required: true },
1157+
test_map: {
1158+
type: Map,
1159+
of: [{
1160+
_id: false,
1161+
num: { type: Number, required: true },
1162+
bool: { type: Boolean, required: true }
1163+
}]
1164+
}
1165+
});
1166+
const Test = db.model('Test', schema);
1167+
1168+
let doc1 = new Test({ name: 'name1', test_map: new Map() });
1169+
await doc1.save();
1170+
1171+
// 1. Refresh the document from the db
1172+
doc1 = await Test.findOne({ _id: doc1._id });
1173+
1174+
// 2. Modify the document (add a new key in the test_map map)
1175+
doc1.test_map.set('key1', []);
1176+
await doc1.save();
1177+
1178+
// 3. Now, the document is wrong in the db and we cannot access the test_map anymore.
1179+
doc1 = await Test.findOne({ _id: doc1._id });
1180+
assert.deepStrictEqual(doc1.toObject().test_map, new Map([['key1', []]]));
1181+
1182+
doc1 = await Test.findOne({ _id: doc1._id }).lean();
1183+
assert.deepStrictEqual(doc1.test_map, { key1: [] });
1184+
});
11531185
});

0 commit comments

Comments
 (0)