Skip to content

Commit

Permalink
Merge pull request #13386 from Automattic/vkarpov15/gh-13327-2
Browse files Browse the repository at this point in the history
fix(document): handle set() from top-level underneath a map of mixed
  • Loading branch information
vkarpov15 authored May 8, 2023
2 parents 59a29a8 + be67d0f commit a2040f6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
34 changes: 24 additions & 10 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,11 @@ Document.prototype.$set = function $set(path, val, type, options) {
// allow changes to sub paths of mixed types
mixed = true;
break;
} else if (schema.$isSchemaMap && schema.$__schemaType instanceof MixedSchema && i < parts.length - 1) {
// Map of mixed and not the last element in the path resolves to mixed
mixed = true;
schema = schema.$__schemaType;
break;
}
}

Expand Down Expand Up @@ -1688,17 +1693,26 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
obj[parts[i]] = val;
}
} else {
if (utils.isPOJO(obj[parts[i]])) {
obj = obj[parts[i]];
} else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) {
obj = obj[parts[i]];
} else if (obj[parts[i]] && !Array.isArray(obj[parts[i]]) && obj[parts[i]].$isSingleNested) {
obj = obj[parts[i]]._doc;
} else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
obj = obj[parts[i]];
const isMap = obj instanceof Map;
let value = isMap ? obj.get(parts[i]) : obj[parts[i]];
if (utils.isPOJO(value)) {
obj = value;
} else if (value && value instanceof Embedded) {
obj = value;
} else if (value && !Array.isArray(value) && value.$isSingleNested) {
obj = value._doc;
} else if (value && Array.isArray(value)) {
obj = value;
} else if (value == null) {
value = {};
if (isMap) {
obj.set(parts[i], value);
} else {
obj[parts[i]] = value;
}
obj = value;
} else {
obj[parts[i]] = obj[parts[i]] || {};
obj = obj[parts[i]];
obj = value;
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12107,6 +12107,24 @@ describe('document', function() {
const fromDb = await Test.findById(x._id).lean();
assert.equal(fromDb.d.x.y, 1);
});

it('can set() from top-level on path underneath map of mixed (gh-13327)', async function() {
const testSchema = new Schema({
c: {
type: Map,
of: 'Mixed'
}
});
const Test = db.model('Test', testSchema);

const x = new Test();
x.set('c.x.y', 1);
assert.strictEqual(x.get('c.x.y'), 1);
await x.save();

const fromDb = await Test.findById(x._id).lean();
assert.equal(fromDb.c.x.y, 1);
});
});

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

0 comments on commit a2040f6

Please sign in to comment.