Skip to content

fix(document+schema): improve handling for setting paths underneath maps, including maps of maps #15477

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

Merged
merged 4 commits into from
Jun 12, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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: 3 additions & 3 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -1302,7 +1302,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
let cur = this._doc;
let curPath = '';
for (i = 0; i < parts.length - 1; ++i) {
cur = cur[parts[i]];
cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]];
curPath += (curPath.length !== 0 ? '.' : '') + parts[i];
if (!cur) {
this.$set(curPath, {});
Expand Down Expand Up @@ -1433,9 +1433,9 @@ Document.prototype.$set = function $set(path, val, type, options) {
setterContext = getDeepestSubdocumentForPath(this, parts, this.schema);
}
if (options != null && options.overwriteImmutable) {
val = schema.applySetters(val, setterContext, false, priorVal, { overwriteImmutable: true });
val = schema.applySetters(val, setterContext, false, priorVal, { path, overwriteImmutable: true });
} else {
val = schema.applySetters(val, setterContext, false, priorVal);
val = schema.applySetters(val, setterContext, false, priorVal, { path });
}
}

Expand Down
22 changes: 18 additions & 4 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1482,10 +1482,24 @@ function getMapPath(schema, path) {
return null;
}
for (const val of schema.mapPaths) {
const _path = val.path;
const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
if (re.test(path)) {
return schema.paths[_path];
const cleanPath = val.path.replace(/\.\$\*/g, '');
if (path === cleanPath || (path.startsWith(cleanPath + '.') && path.slice(cleanPath.length + 1).indexOf('.') === -1)) {
return val;
} else if (val.schema && path.startsWith(cleanPath + '.')) {
let remnant = path.slice(cleanPath.length + 1);
remnant = remnant.slice(remnant.indexOf('.') + 1);
return val.schema.paths[remnant];
} else if (val.$isSchemaMap && path.startsWith(cleanPath + '.')) {
let remnant = path.slice(cleanPath.length + 1);
remnant = remnant.slice(remnant.indexOf('.') + 1);
const presplitPath = val.$__schemaType._presplitPath;
if (remnant.indexOf('.') === -1 && presplitPath[presplitPath.length - 1] === '$*') {
// Handle map of map of primitives
return val.$__schemaType;
} else if (remnant.indexOf('.') !== -1 && val.$__schemaType.schema && presplitPath[presplitPath.length - 1] === '$*') {
// map of map of subdocs (recursive)
return val.$__schemaType.schema.path(remnant.slice(remnant.indexOf('.') + 1));
}
}
}

Expand Down
52 changes: 52 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14496,6 +14496,58 @@ describe('document', function() {
assert.strictEqual(err.name, 'VersionError');
assert.ok(err.message.includes('texts'));
});

it('handles direct map manipulation with nested set() calls (gh-15461)', async function() {
const MetaSchema = new mongoose.Schema({
items: {
type: Map,
of: new mongoose.Schema({
field: { type: String, required: true },
arr: { type: [Number] }
}, { _id: false }),
default: new Map()
},
nested: {
type: Map,
of: new mongoose.Schema({ map: { type: Map, of: Number } }, { _id: false }),
default: new Map()
}
});
const MetaModel = db.model('MetaModel', MetaSchema);
await MetaModel.create({
items: new Map([
['m1', { field: 'field1', arr: [1, 2], num: 2 }],
['m2', { field: 'field2', arr: [] }]
]),
nested: new Map([
[
'key',
{ map: new Map([['k7', 7], ['k8', 8], ['k9', 9]]) }
],
['key2', { map: new Map([['k7', 7]]) }]
])
});
const item = await MetaModel.findOne();

item.set('items.m1.field', 'changed');
item.set('items.m2.field', 'replaced');
item.set('items.m2.arr', [1]);
item.set('items.m3', { field: 'field3', arr: [4] });
item.set('nested.inserted', { map: new Map([['a1', 1]]) });
item.set('nested.inserted2.map', new Map([['a1', 1]]));

await item.save();

// Verify changes were saved
const updatedItem = await MetaModel.findOne();
assert.strictEqual(updatedItem.items.get('m1').field, 'changed');
assert.strictEqual(updatedItem.items.get('m2').field, 'replaced');
assert.deepStrictEqual(updatedItem.items.get('m2').arr, [1]);
assert.strictEqual(updatedItem.items.get('m3').field, 'field3');
assert.deepStrictEqual(updatedItem.items.get('m3').arr, [4]);
assert.strictEqual(updatedItem.nested.get('inserted').map.get('a1'), 1);
assert.strictEqual(updatedItem.nested.get('inserted2').map.get('a1'), 1);
});
});

describe('Check if instance function that is supplied in schema option is available', function() {
Expand Down
71 changes: 71 additions & 0 deletions test/schema.path.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
'use strict';

const Schema = require('../lib/schema');
const assert = require('assert');

describe('Schema.prototype.path()', function() {
it('gets paths underneath maps', function() {
const schema = new Schema({
myMap: {
type: Map,
of: String
}
});

assert.equal(schema.path('myMap').$__schemaType.instance, 'String');
assert.equal(schema.path('myMap.$*').instance, 'String');
});

it('gets paths underneath maps of subdocuments', function() {
const personSchema = new Schema({ name: String, age: Number });
const schema = new Schema({
myMap: {
type: Map,
of: personSchema
}
});

assert.equal(schema.path('myMap').$__schemaType.schema.path('name').instance, 'String');
assert.equal(schema.path('myMap').$__schemaType.schema.path('age').instance, 'Number');

assert.equal(schema.path('myMap.key.name').instance, 'String');
assert.equal(schema.path('myMap.key.age').instance, 'Number');
assert.equal(schema.path('myMap.key.age').instance, 'Number');
});

it('gets paths underneath maps of maps', function() {
const schema = new Schema({
myMap: {
type: Map,
of: {
type: Map,
of: String
}
}
});

assert.equal(schema.path('myMap').$__schemaType.instance, 'Map');
assert.equal(schema.path('myMap.key').instance, 'Map');
assert.equal(schema.path('myMap.key.key2').instance, 'String');
assert.ok(!schema.path('myMap.key.key2.key3'));
});

it('gets paths underneath maps of maps of subdocs', function() {
const schema = new Schema({
myMap: {
type: Map,
of: {
type: Map,
of: new Schema({
name: String
})
}
}
});

assert.equal(schema.path('myMap').$__schemaType.instance, 'Map');
assert.equal(schema.path('myMap.key').instance, 'Map');
assert.equal(schema.path('myMap.key.key2.name').instance, 'String');
assert.ok(!schema.path('myMap.key.key2.key3'));
});
});
49 changes: 49 additions & 0 deletions test/schema.pathType.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';

const Schema = require('../lib/schema');
const assert = require('assert');

describe('Schema.prototype.pathType()', function() {
it('gets paths underneath maps', function() {
const schema = new Schema({
myMap: {
type: Map,
of: String
}
});

assert.equal(schema.pathType('myMap'), 'real');
assert.equal(schema.pathType('myMap.key'), 'real');
});

it('gets paths underneath maps of subdocuments', function() {
const personSchema = new Schema({ name: String, age: Number });
const schema = new Schema({
myMap: {
type: Map,
of: personSchema
}
});

assert.equal(schema.pathType('myMap'), 'real');
assert.equal(schema.pathType('myMap.key'), 'real');
assert.equal(schema.pathType('myMap.key.name'), 'real');
assert.equal(schema.pathType('myMap.key.age'), 'real');
});

it('gets paths underneath maps of maps', function() {
const schema = new Schema({
myMap: {
type: Map,
of: {
type: Map,
of: String
}
}
});

assert.equal(schema.pathType('myMap'), 'real');
assert.equal(schema.pathType('myMap.key'), 'real');
assert.equal(schema.pathType('myMap.key.key2'), 'real');
});
});