Prerequisites
Mongoose version
>=8.19.2
Node.js version
v22.22.0
MongoDB server version
7.0.21
Typescript version (if applicable)
No response
Description
Starting with Mongoose 8.19.2, findOneAndUpdate with upsert: true no longer merges fields defined in the filter into the created document if those fields utilize dot notation (e.g., 'nested.field': 'value').
In previous versions, Mongoose inferred that the filter criteria should be part of the inserted document. Now, the document is created without these nested fields, resulting in data loss for fields defined solely in the query filter.
Steps to Reproduce
Run the following script. It passes on Mongoose < 8.19.2,
fails on mongoose >=8.19.2.
async function reprduce() {
const extraPropsSchema = new mongoose.Schema( { location: String } );
const schema = new Schema({
nickName: String,
lastName: String,
// extraProps must have subSchema type, with default value to reproduce
extraProps: { type: extraPropsSchema, default: {}}
});
const Model = mongoose.model('Test', schema);
// Filter uses dot notation for a nested field
const filter = { "extraProps.location": "Foo" };
const update = {
$setOnInsert: { nickName: "Roo" },
$set: { lastName: "Goo" }
};
const options = { upsert: true, new: true, setDefaultsOnInsert: true };
const res = await Model.findOneAndUpdate(filter, update, options);
console.log('Created document:', res);
assert.equal(res.lastName, "Goo"); // pass
assert.equal(res.nickName, "Roo"); // pass
assert.equal(res.extraProps?.location, "Foo", "Dot-notation filter field was not merged into insert"); //❌ FAILS HERE in mongoose >=8.19.2
}
Expected Behavior
The created document contains
{ extraProps: { location: "Foo" } }
since it was required by the filter.
Actual Behavior
The created document is missing the nested field:
{
_id: new ObjectId("..."),
nickName: 'Roo',
lastName: 'Goo',
// extraProps is undefined or empty
}
Prerequisites
Mongoose version
>=8.19.2
Node.js version
v22.22.0
MongoDB server version
7.0.21
Typescript version (if applicable)
No response
Description
Starting with Mongoose 8.19.2,
findOneAndUpdatewithupsert: trueno longer merges fields defined in the filter into the created document if those fields utilize dot notation (e.g., 'nested.field': 'value').In previous versions, Mongoose inferred that the filter criteria should be part of the inserted document. Now, the document is created without these nested fields, resulting in data loss for fields defined solely in the query filter.
Steps to Reproduce
Run the following script. It passes on Mongoose < 8.19.2,
fails on mongoose >=8.19.2.
Expected Behavior
The created document contains
since it was required by the filter.
Actual Behavior
The created document is missing the nested field: