#16539·mongoose

Map of arrays: set() followed by push(), pull() or addToSet() saves against the old array

Author: luantaraschiCreated Sep 29, 2026Updated Sep 29, 2026

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

9.10.3 (master at d5841fe6)

Node.js version

22.23.2

MongoDB server version

8.2.12

Description

If you replace an array in a Map with set() and then call push(), pull() or addToSet() on it before save(), only the atomic operator is sent. MongoDB applies it to the array that is already stored, so the array passed to set() is lost. In memory the array is [7, 8], the database ends up with [1, 8].

Assigning an array straight onto a document path doesn't do this, because Document#$__set registers a $set atomic for it (gh-1126). Map#set() only calls markModified().

The same happens with pull() (start from [1, 2], set('math', [7, 1]), pull(1): the database keeps [2] instead of [7]) and with addToSet(). A Map of document arrays behaves the same way.

Steps to Reproduce

javascript
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
  scores: { type: Map, of: [Number] }
});
const Test = mongoose.model('Test', schema);

async function run() {
  await mongoose.connect('mongodb://127.0.0.1:27017/test');
  await Test.deleteMany({});

  const { _id } = await Test.create({ scores: { math: [1] } });

  const doc = await Test.findById(_id);
  doc.scores.set('math', [7]);
  doc.scores.get('math').push(8);
  console.log('in memory:', doc.scores.get('math').toObject());
  console.log('changes:', JSON.stringify(doc.$getChanges()));
  await doc.save();

  const raw = await Test.collection.findOne({ _id });
  console.log('in database:', raw.scores.math);
  await mongoose.disconnect();
}

run();

Output:

in memory: [ 7, 8 ]
changes: {"$push":{"scores.math":{"$each":[8]}},"$inc":{"__v":1}}
in database: [ 1, 8 ]

Expected Behavior

The database has [7, 8], the same as the in-memory value.

I have a small fix with tests and will open a PR.