-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can not update sub schema to empty object #14420
Comments
This may be expected behavior but labeling as confirmed bug just in case. I believe if you want to remove data from a document you have to set it to const mongoose = require('mongoose');
const SubSchema = new mongoose.Schema({
name: {type: String}
}, { _id: false });
const MainSchema = new mongoose.Schema({
sub: {
type: SubSchema,
}
});
const MainModel = mongoose.model('Main', MainSchema);
run().catch(e => console.log(e))
async function run() {
await mongoose.connect('mongodb://localhost:27017/mongoose_test');
await mongoose.connection.dropDatabase();
console.log(mongoose.version);
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 an expected empy object', 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
} |
Why did you put _id:false in the schema if you wanted to find a document via findById? Maybe try removing the _id:false from the schema and see what happens? |
Thank you for looking in to this @IslandRhythms. When did this behaviour change? Couldn't find any breaking changes in the change log. This worked fine in 6.x. I also find it confusing that the local document has a different state (correct state in my mind) and the change tracking stays that there is a change? But this change is not saved to the database. You are correct that setting it to
The |
I recommend you take a look at this issue. |
fix(model): improve update minimizing to only minimize top-level properties in the update
Prerequisites
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
Expected Behavior
The change in the local document to be updated in the database.
The text was updated successfully, but these errors were encountered: