You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/faq.md
+45Lines changed: 45 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -430,6 +430,51 @@ await query.clone(); // Works
430
430
Note: Mongoose v7+ no longer supports callbacks. If you're seeing duplicate queries in older code,
431
431
it may be due to mixing callbacks and promises, which is no longer possible in current versions.
432
432
433
+
<hrid="divergent-array-error" />
434
+
435
+
<aclass="anchor"href="#divergent-array-error">**Q**</a>. What does `DivergentArrayError` mean and how do I fix it?
436
+
437
+
**A**. Mongoose throws `DivergentArrayError` when you call `document.save()` to update an array that was only partially loaded, for example:
438
+
439
+
* the array was selected using an `$elemMatch` projection
440
+
* the array was populated using `populate()` with `skip`, `limit`, query conditions, or options that exclude `_id`
441
+
* the save would result in MongoDB performing a `$set` or `$pop` of the entire array
442
+
443
+
Because only part of the array is in memory, Mongoose can't safely reconstruct the full array to send back to MongoDB without risking data loss, so it throws `DivergentArrayError` instead.
444
+
445
+
For example:
446
+
447
+
```javascript
448
+
constdoc=awaitBlogPost.findOne(
449
+
{ _id },
450
+
{ comments: { $elemMatch: { flagged:true } } }
451
+
);
452
+
453
+
doc.comments[0].text='Updated';
454
+
awaitdoc.save();
455
+
```
456
+
457
+
To fix this error, either:
458
+
459
+
(1) Load the full array before modifying and saving:
460
+
461
+
```javascript
462
+
constdoc=awaitBlogPost.findById(_id);
463
+
doc.comments.id(commentId).text='Updated';
464
+
awaitdoc.save();
465
+
```
466
+
467
+
(2) Or use `updateOne()` / `updateMany()` with positional operators or `arrayFilters` so MongoDB can update the array atomically without requiring the full array on the document:
468
+
469
+
```javascript
470
+
awaitBlogPost.updateOne(
471
+
{ _id, 'comments._id': commentId },
472
+
{ $set: { 'comments.$.text':'Updated' } }
473
+
);
474
+
```
475
+
476
+
The same guidance applies if you populated an array with `skip`, `limit`, query conditions, or excluded `_id`: avoid calling `save()` to update that partially loaded array; instead, re-query without those options or use an update operation as shown above.
0 commit comments