Skip to content

Commit

Permalink
fix(documentarray): set correct document array path if making map of …
Browse files Browse the repository at this point in the history
…document arrays

Fix #12997
  • Loading branch information
vkarpov15 committed Mar 6, 2023
1 parent a9a838c commit 060c889
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/schema/documentarray.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,30 +416,32 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {

options = options || {};

const path = options.path || this.path;

if (!Array.isArray(value)) {
if (!init && !DocumentArrayPath.options.castNonArrays) {
throw new CastError('DocumentArray', value, this.path, null, this);
}
// gh-2442 mark whole array as modified if we're initializing a doc from
// the db and the path isn't an array in the document
if (!!doc && init) {
doc.markModified(this.path);
doc.markModified(path);
}
return this.cast([value], doc, init, prev, options);
}

// We need to create a new array, otherwise change tracking will
// update the old doc (gh-4449)
if (!options.skipDocumentArrayCast || utils.isMongooseDocumentArray(value)) {
value = new MongooseDocumentArray(value, this.path, doc);
value = new MongooseDocumentArray(value, path, doc);
}

if (prev != null) {
value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {};
}

if (options.arrayPathIndex != null) {
value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex;
value[arrayPathSymbol] = path + '.' + options.arrayPathIndex;
}

const rawArray = utils.isMongooseDocumentArray(value) ? value.__array : value;
Expand Down
18 changes: 18 additions & 0 deletions test/types.documentarray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -762,4 +762,22 @@ describe('types.documentarray', function() {

assert.ok(doc.subDocArray[0]._id instanceof mongoose.Types.ObjectId);
});

it('gets correct path when underneath map (gh-12997)', function() {
const mapArraySchema = Schema({
myMap: {
type: Map,
of: [Schema({ name: String })]
}
});

const Model = db.model('Test', mapArraySchema);
const doc = new Model({
myMap: {
foo: [{ name: 'bar' }]
}
});

assert.equal(doc.myMap.get('foo').$path(), 'myMap.foo');
});
});

0 comments on commit 060c889

Please sign in to comment.