Skip to content

Can not update sub schema to empty object #14420

Closed

Description

Prerequisites

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

Mongoose version

8.2.1

Node.js version

20.11.1

MongoDB server version

4.4

Typescript version (if applicable)

No response

Description

We ran in to an issue while migrating from mongoose 6 when trying to set the path of a sub scehma to an empty object (clearing all data). The change is reflected in the local document and the modifiedPaths() says that the attribute has been changed. But the change is not saved in the database.

Steps to Reproduce

await mongoose.connect('mongodb://localhost:27017/mongoose_test');
console.log(mongoose.version);

const SubSchema = new mongoose.Schema({
	name: {type: String}
}, { _id: false });

const MainSchema = new mongoose.Schema({
	sub: { 
			type: SubSchema,
		}
});

const MainModel = mongoose.model('Main', MainSchema);

const doc = new MainModel({ sub: { name: 'Hello World' } });
console.log('init', doc.sub); // { name: 'Hello World' }
await doc.save();

doc.set({ sub: {} });
await doc.save();
console.log('save', doc.sub); // {} empty as expected

const savedDoc = await MainModel.findById(doc.id).orFail();
console.log('findById', savedDoc.sub); // { name: 'Hello World' } still has old value

Expected Behavior

The change in the local document to be updated in the database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions