fix(document): throw error if overwriting array selected with $slice - #16313
Merged
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
Extends divergent-array detection so document.save() throws DivergentArrayError when an array selected via a $slice projection would be overwritten via a $set atomic, while allowing safe $push/$pull/$pop/$addToSet updates. Fixes #2432.
Changes:
checkDivergentArray()now also flags arrays selected with$slicewhen modifications resolve to a$setatomic.DivergentArrayErrormessage updated to mention$slice.- Adds tests covering
$set,$push,$pull,$pop,$addToSetbehavior on$slice-selected arrays.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| lib/document.js | Adds $slice projection check in checkDivergentArray() returning the top path when atomics contain $set. |
| lib/error/divergentArray.js | Updates error message to mention $slice projection. |
| test/model.field.selection.test.js | Adds tests verifying divergent error for $set and successful saves for $push/$pull/$pop/$addToSet. |
hasezoey
approved these changes
Jun 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fix #2432
Summary
Currently, if you use a $elemMatch projection and try to save, Mongoose will throw a DivergentArrayError:
The crux of #2432 is we should do that for
$sliceas well. But only for$setatomics - ifsave()would just$pushor$pullor$popfrom the array then that won't overwrite the existing array.Examples