Skip to content
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

Impossible to delete values in array field #770

Open
louisremi opened this issue Jan 14, 2022 · 0 comments
Open

Impossible to delete values in array field #770

louisremi opened this issue Jan 14, 2022 · 0 comments

Comments

@louisremi
Copy link

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
image

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);
      }
    });
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant