-
Notifications
You must be signed in to change notification settings - Fork 27
Description
Expected behavior
I have a collection with several array fields:
const schema = Mongoose.Schema({
_id: { … },
…
phones: [{ type: String }],
websites: [{ type: String }],
emails: [{ type: String }],
})
The edit UI allows users to add and delete values in this array
When users try to delete values, it fails, the old values reappear after clicking on the save button. It only works if the user replaces the value deleted with a new one.
The issue appears to originate from the flattenRecordDataForUpdates function which turns the value { websites: [ 'https://second-website.com' ] }
into { 'websites.0': 'https://second-website.com' }
which fails to delete values I want to get rid of. This happens while I didn't add websites
to the fieldsToFlatten
config of my collection.
Actual behavior
The values deleted by the user should be deleted from the DB
Context
TODO: Please provide any relevant information about your setup.
- Package Version: 8.5.0
- Express Version: ???
- Mongoose Version: 6.0.10
- MongoDB Version: ???
Workaround
As a workaround, I've added the following findOneAndUpdate hook to my Mongoose model:
.pre("findOneAndUpdate", async function () {
["websites", "phones", "emails"].forEach((fieldName) => {
if (this.get(`${fieldName}.0`)) {
const values = [];
let val;
while (
(val = this.get(`${fieldName}.${values.length}`)) !== undefined
) {
this.set(`${fieldName}.${values.length}`, undefined);
values.push(val);
}
this.set(fieldName, values);
}
});
});