Skip to content

Support updating/deleting with associations in a single step #11836

Description

@papb

Issue Description

Note: I am creating this issue to centralize a topic that often appears in different issues.

Is your feature request related to a problem? Please describe.

Similarly to the possibility of running a single create call to create associated object together with the main object, users often want to update / delete an object with associated objects as well, such as in #7703, #9678 and sequelize/sequelize-typescript#309. I am opening this issue to track all this in a single place.

Currently, our docs clarify that this is not possible.

In contrast, performing updates and deletions involving nested objects is currently not possible. For that, you will have to perform each separate action explicitly.

Describe the solution you'd like

I don't have a clear concrete idea in mind. In fact, I think this is the biggest challenge for implementing this - to decide how exactly this will work. See this comment on #6808 and this comment on #5471.

Why should this be in Sequelize

This is a complex task that would be great to have covered by the ORM itself.

Describe alternatives/workarounds you've considered

The alternative/workaround is to do every create/update/delete by hand on a case-by-case basis...

Additional context

Very related issues: #6808 and #5471
Other related issues:
#9199
#9233
#7703
#11699

Issue Template Checklist

Is this issue dialect-specific?

  • No. This issue is relevant to Sequelize as a whole.
  • Yes. This issue only applies to the following dialect(s): XXX, YYY, ZZZ

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. added
    hard
    status: in discussion
    type: feature
    on Jan 16, 2020
  2. Nitemaeric commented on Jan 29, 2020

    @Nitemaeric

    Hi @papb , I'm a long time Ruby on Rails developer and therefore I have some input regarding this comment: #6808 (comment)

    ActiveRecord (RoR's ORM) goes by this rule of thumb:

    1. If the nested association parameters does not contain the primaryKey of that record, it will create a new record.
    2. If the nested association parameters contain the primaryKey of that record, it will update the record.
    3. If the nested association parameters contain both the primaryKey and the _destroy key has a truthy value, ActiveRecord will destroy the record.

    Again with JSON examples:

    Assuming all primary keys in this example are id.

    1. Create
    {
      id: 1,
      subcollection: [
        {
          attributeA: 'new value for attributeA' // There is no primary key in this object
        }
      ]
    }
    1. Update
    {
      id: 1,
      subcollection: [
        {
          id: 2,
          attributeA: 'new value for attributeA on subcollection id = 2' // The primary key is present in this case
        }
      ]
    }
    1. Destroy
    {
      id: 1,
      subcollection: [
        {
          id: 2,
          attributeA: 'new value for attributeA on subcollection id = 2' // This is ignored
          _destroy: true // Primary key is present and the _destroy key is both present and truthy
        }
      ]
    }

    Hope it gives some direction towards bringing this functionality to Sequelize.

  3. sergiomendonca commented on Jul 8, 2020

    @sergiomendonca

    Up!

  4. wakeupmh commented on Dec 3, 2020

    @wakeupmh

    Does this remain unsolved?

  5. filipesarturi commented on Dec 6, 2020

    @filipesarturi

    I implemented the fillAndSave method in my base class of my models to help me in these cases. So I can do things like:

    await model.fillAndSave([
      id: 1,
      foo: 'bar',
      someAssociation: [
        {
          id: 2,
          name: 'existing object'
        },
    
        {
          name: 'new object'
        },
      ]
    ])

    Model:

    import Sequelize from 'sequelize'
    
    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase().concat(string.slice(1))
    }
    
    export default class Model extends Sequelize.Model {
      async fill(values) {
        const attributes = this.constructor.attributes
        const associations = this.constructor.associations
        const getFilledModelInstance = async ({ model, data }) => {
          let modelInstance = data
    
          if (!(modelInstance instanceof model)) modelInstance = new model()
    
          return modelInstance.fill(data)
        }
    
        if (this.associationsData === undefined) this.associationsData = {}
    
        for (const key in values) {
          const association = associations[key]
          const value = values[key]
    
          if (!association) {
            if (attributes[key] !== undefined) this.setDataValue(key, value)
            else this[key] = value
            continue
          }
    
          const model = association?.target
    
          this.associationsData[key] =
            Array.isArray(value) === true
              ? await Promise.all(
                  value.map(data => getFilledModelInstance({ model, data }))
                )
              : await getFilledModelInstance({ model, data: value })
        }
    
        this.isNewRecord = this.getIsNewRecord()
    
        return this
      }
    
      getThroughModelsName() {
        const associations = this.constructor.associations
        const throughModelsName = []
    
        for (const associationName in associations) {
          const association = associations[associationName]
    
          if (association.throughModel !== undefined)
            throughModelsName.push(association.throughModel.name)
        }
    
        return throughModelsName
      }
    
      async deepSave({ parent, associationName } = {}) {
        let modelInstance = this
    
        const associationsData = modelInstance.associationsData ?? {}
    
        if (modelInstance.isNewRecord === true && parent) {
          const createMethodName = parent.constructor.getMethodName(
            'create',
            associationName,
            'singular'
          )
          const createValue = modelInstance?.toObject?.() ?? modelInstance
          const throughModelsName = parent.getThroughModelsName()
    
          let createOptions = {}
    
          throughModelsName.some(throughModelName => {
            const throughValue = modelInstance[throughModelName]
    
            if (throughValue !== undefined) {
              createOptions = {
                through: throughValue
              }
    
              return true
            }
    
            return false
          })
    
          modelInstance = await parent[createMethodName](createValue, createOptions)
        } else {
          await modelInstance.save()
        }
    
        for (const associationName in associationsData) {
          let value = associationsData[associationName]
    
          value =
            Array.isArray(value) === true
              ? await Promise.all(
                  value.map(item =>
                    item.deepSave({
                      parent: modelInstance,
                      associationName
                    })
                  )
                )
              : await value.deepSave({
                  parent: modelInstance,
                  associationName
                })
    
          const setMethodName = modelInstance.constructor.getMethodName(
            'set',
            associationName
          )
    
          await modelInstance?.[setMethodName]?.(value)
        }
    
        return modelInstance
      }
    
      async fillAndSave(values) {
        await this.fill(values)
    
        return this.deepSave()
      }
    
      getIsNewRecord() {
        const primaryKeyAttributes = this.constructor.primaryKeyAttributes ?? []
    
        if (primaryKeyAttributes.length === 0) return
    
        return primaryKeyAttributes.some(primaryKeyAttribute =>
          [undefined, null].includes(this[primaryKeyAttribute])
        )
      }
    
      static getMethodName(prefix = '', value = '', mode) {
        let methodName = value
    
        switch (mode) {
          case 'plural':
          case 'pluralize':
            const { plural: pluralize } = require('pluralize')
    
            methodName = pluralize(methodName)
            break
    
          case 'singular':
          case 'singularize':
            const { singular: singularize } = require('pluralize')
    
            methodName = singularize(methodName)
            break
        }
    
        methodName = capitalizeFirstLetter(methodName)
        methodName = `${prefix}${methodName}`
    
        return methodName
      }
    }

    I hope this helps in something ... 😉🙏

  6. LeslieLei commented on Jan 14, 2021

    @LeslieLei

    I implemented the fillAndSave method in my base class of my models to help me in these cases. So I can do things like:

    await model.fillAndSave([
      id: 1,
      foo: 'bar',
      someAssociation: [
        {
          id: 2,
          name: 'existing object'
        },
    
        {
          name: 'new object'
        },
      ]
    ])

    Model:

    import Sequelize from 'sequelize'
    
    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase().concat(string.slice(1))
    }
    
    export default class Model extends Sequelize.Model {
      async fill(values) {
        const attributes = this.constructor.attributes
        const associations = this.constructor.associations
        const getFilledModelInstance = async ({ model, data }) => {
          let modelInstance = data
    
          if (!(modelInstance instanceof model)) modelInstance = new model()
    
          return modelInstance.fill(data)
        }
    
        if (this.associationsData === undefined) this.associationsData = {}
    
        for (const key in values) {
          const association = associations[key]
          const value = values[key]
    
          if (!association) {
            if (attributes[key] !== undefined) this.setDataValue(key, value)
            else this[key] = value
            continue
          }
    
          const model = association?.target
    
          this.associationsData[key] =
            Array.isArray(value) === true
              ? await Promise.all(
                  value.map(data => getFilledModelInstance({ model, data }))
                )
              : await getFilledModelInstance({ model, data: value })
        }
    
        this.isNewRecord = this.getIsNewRecord()
    
        return this
      }
    
      getThroughModelsName() {
        const associations = this.constructor.associations
        const throughModelsName = []
    
        for (const associationName in associations) {
          const association = associations[associationName]
    
          if (association.throughModel !== undefined)
            throughModelsName.push(association.throughModel.name)
        }
    
        return throughModelsName
      }
    
      async deepSave({ parent, associationName } = {}) {
        let modelInstance = this
    
        const associationsData = modelInstance.associationsData ?? {}
    
        if (modelInstance.isNewRecord === true && parent) {
          const createMethodName = parent.constructor.getMethodName(
            'create',
            associationName,
            'singular'
          )
          const createValue = modelInstance?.toObject?.() ?? modelInstance
          const throughModelsName = parent.getThroughModelsName()
    
          let createOptions = {}
    
          throughModelsName.some(throughModelName => {
            const throughValue = modelInstance[throughModelName]
    
            if (throughValue !== undefined) {
              createOptions = {
                through: throughValue
              }
    
              return true
            }
    
            return false
          })
    
          modelInstance = await parent[createMethodName](createValue, createOptions)
        } else {
          await modelInstance.save()
        }
    
        for (const associationName in associationsData) {
          let value = associationsData[associationName]
    
          value =
            Array.isArray(value) === true
              ? await Promise.all(
                  value.map(item =>
                    item.deepSave({
                      parent: modelInstance,
                      associationName
                    })
                  )
                )
              : await value.deepSave({
                  parent: modelInstance,
                  associationName
                })
    
          const setMethodName = modelInstance.constructor.getMethodName(
            'set',
            associationName
          )
    
          await modelInstance?.[setMethodName]?.(value)
        }
    
        return modelInstance
      }
    
      async fillAndSave(values) {
        await this.fill(values)
    
        return this.deepSave()
      }
    
      getIsNewRecord() {
        const primaryKeyAttributes = this.constructor.primaryKeyAttributes ?? []
    
        if (primaryKeyAttributes.length === 0) return
    
        return primaryKeyAttributes.some(primaryKeyAttribute =>
          [undefined, null].includes(this[primaryKeyAttribute])
        )
      }
    
      static getMethodName(prefix = '', value = '', mode) {
        let methodName = value
    
        switch (mode) {
          case 'plural':
          case 'pluralize':
            const { plural: pluralize } = require('pluralize')
    
            methodName = pluralize(methodName)
            break
    
          case 'singular':
          case 'singularize':
            const { singular: singularize } = require('pluralize')
    
            methodName = singularize(methodName)
            break
        }
    
        methodName = capitalizeFirstLetter(methodName)
        methodName = `${prefix}${methodName}`
    
        return methodName
      }
    }

    I hope this helps in something ... 😉🙏

    how can i implement this

  7. klausXR commented on Apr 9, 2021

    @klausXR

    Plus one for this functionality. I believe TypeORM and Mikro-Orm both support this and I feel like it is rather hard to manage write operations without this functionality.

    Also, a lot of the ideas for the Repository pattern from DDD and similar methodologies sort of rely on this - its not impossible without it, but it involves much more code.

    Also, I don't know if the documentation for association methods is written poorly, but I couldn't get the set methods to work for associations besides belongsToMany.

    For example, for One to many relationships, I would like to do User.setAddresses([ Model, Model ]), where the model is an instance build with Address.build(data).

    I'd like the ones that I passed to be persisted and anything else to be unassociated, but the set method does not work like that.

    I frequently get myself into similar situations, which are harder to handle without the aforementioned functionality.

    I create a User with two addresses.

    Then, later on, somebody tries to update the user with 2 new addresses ( the two old ones must be unassociated )

    The set methods expects me to have "created" instances, but in order to create it without the association, I would need to have an user address with null column for address.userId.

    If it worked with models and I was able to save it in one go, like in the other more popular orms, it would be much easier to handle.

    const user = new User(userData)
    user.addresses = userData.addresses.map(address => new Address(address))
    await user.save()

    versus whatever I have to do in Sequelize to achieve the same functionality ( I couldn't figure it out )

  8. microvn commented on May 2, 2021

    @microvn

    up

  9. sun-slaven commented on Aug 3, 2021

    @sun-slaven

    not resolved yet?

  10. joaquinodz commented on Aug 23, 2021

    @joaquinodz

    I implemented the fillAndSave method in my base class of my models to help me in these cases. So I can do things like:

    await model.fillAndSave([
      id: 1,
      foo: 'bar',
      someAssociation: [
        {
          id: 2,
          name: 'existing object'
        },
    
        {
          name: 'new object'
        },
      ]
    ])

    Model:

    import Sequelize from 'sequelize'
    
    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase().concat(string.slice(1))
    }
    
    export default class Model extends Sequelize.Model {
      async fill(values) {
        const attributes = this.constructor.attributes
        const associations = this.constructor.associations
        const getFilledModelInstance = async ({ model, data }) => {
          let modelInstance = data
    
          if (!(modelInstance instanceof model)) modelInstance = new model()
    
          return modelInstance.fill(data)
        }
    
        if (this.associationsData === undefined) this.associationsData = {}
    
        for (const key in values) {
          const association = associations[key]
          const value = values[key]
    
          if (!association) {
            if (attributes[key] !== undefined) this.setDataValue(key, value)
            else this[key] = value
            continue
          }
    
          const model = association?.target
    
          this.associationsData[key] =
            Array.isArray(value) === true
              ? await Promise.all(
                  value.map(data => getFilledModelInstance({ model, data }))
                )
              : await getFilledModelInstance({ model, data: value })
        }
    
        this.isNewRecord = this.getIsNewRecord()
    
        return this
      }
    
      getThroughModelsName() {
        const associations = this.constructor.associations
        const throughModelsName = []
    
        for (const associationName in associations) {
          const association = associations[associationName]
    
          if (association.throughModel !== undefined)
            throughModelsName.push(association.throughModel.name)
        }
    
        return throughModelsName
      }
    
      async deepSave({ parent, associationName } = {}) {
        let modelInstance = this
    
        const associationsData = modelInstance.associationsData ?? {}
    
        if (modelInstance.isNewRecord === true && parent) {
          const createMethodName = parent.constructor.getMethodName(
            'create',
            associationName,
            'singular'
          )
          const createValue = modelInstance?.toObject?.() ?? modelInstance
          const throughModelsName = parent.getThroughModelsName()
    
          let createOptions = {}
    
          throughModelsName.some(throughModelName => {
            const throughValue = modelInstance[throughModelName]
    
            if (throughValue !== undefined) {
              createOptions = {
                through: throughValue
              }
    
              return true
            }
    
            return false
          })
    
          modelInstance = await parent[createMethodName](createValue, createOptions)
        } else {
          await modelInstance.save()
        }
    
        for (const associationName in associationsData) {
          let value = associationsData[associationName]
    
          value =
            Array.isArray(value) === true
              ? await Promise.all(
                  value.map(item =>
                    item.deepSave({
                      parent: modelInstance,
                      associationName
                    })
                  )
                )
              : await value.deepSave({
                  parent: modelInstance,
                  associationName
                })
    
          const setMethodName = modelInstance.constructor.getMethodName(
            'set',
            associationName
          )
    
          await modelInstance?.[setMethodName]?.(value)
        }
    
        return modelInstance
      }
    
      async fillAndSave(values) {
        await this.fill(values)
    
        return this.deepSave()
      }
    
      getIsNewRecord() {
        const primaryKeyAttributes = this.constructor.primaryKeyAttributes ?? []
    
        if (primaryKeyAttributes.length === 0) return
    
        return primaryKeyAttributes.some(primaryKeyAttribute =>
          [undefined, null].includes(this[primaryKeyAttribute])
        )
      }
    
      static getMethodName(prefix = '', value = '', mode) {
        let methodName = value
    
        switch (mode) {
          case 'plural':
          case 'pluralize':
            const { plural: pluralize } = require('pluralize')
    
            methodName = pluralize(methodName)
            break
    
          case 'singular':
          case 'singularize':
            const { singular: singularize } = require('pluralize')
    
            methodName = singularize(methodName)
            break
        }
    
        methodName = capitalizeFirstLetter(methodName)
        methodName = `${prefix}${methodName}`
    
        return methodName
      }
    }

    I hope this helps in something ... 😉🙏

    Quick Fix: const attributes = this.constructor.attributes -> const attributes = this.constructor.tableAttributes

    I think it was modified at some point ¯_(ツ)_/¯

  11. aclarembeau commented on Sep 30, 2021

    @aclarembeau

    Personally, I ended up writing my own utility function:

    async deepSave(model) => {
      for (let key in model.dataValues) {
        let startingWithMaj = key[0] == key[0].toUpperCase();
        let endingWithS = key.slice(-1) == "s";
        if (startingWithMaj && endingWithS) {
          // Identify what to upsert
          let newValues = model.dataValues[key];
          let oldValues = model._previousDataValues[key];
          let newIds = newValues.map((x) => x.id);
          let oldIds = oldValues.map((x) => x.id);
    
          let toCreate = newValues.filter((x) => !x.id);
          let toDelete = oldValues.filter((x) => !newIds.includes(x.id));
    
          let toUpdate = newValues.filter((x) => oldIds.includes(x.id));
    
          // Process to upsert
          model[key] = [];
          for (let elem of toDelete) {
            await elem.destroy();
          }
    
          for (let elem of toCreate) {
            model[key].push(await elem.constructor.create({ ...elem.dataValues, [model.constructor.name.toString() + "Id"]: model.id }));
          }
          for (let elem of toUpdate) {
            model[key].push(await elem.save());
          }
    
          // Update dataValues for serialization
          model.dataValues[key] = model[key];
        }
      }
      await model.save();
    
      return model;
    }

    It's probably not as flexible/complete as the other solution in this thread. But, as it's simpler, it can serve as a basis if someone wants to extend it :)

  12. k0dsubs commented on Nov 2, 2021

    @k0dsubs

    Personally, I ended up writing my own utility function:

    async deepSave(model) => {
      for (let key in model.dataValues) {
        let startingWithMaj = key[0] == key[0].toUpperCase();
        let endingWithS = key.slice(-1) == "s";
        if (startingWithMaj && endingWithS) {
          // Identify what to upsert
          let newValues = model.dataValues[key];
          let oldValues = model._previousDataValues[key];
          let newIds = newValues.map((x) => x.id);
          let oldIds = oldValues.map((x) => x.id);
    
          let toCreate = newValues.filter((x) => !x.id);
          let toDelete = oldValues.filter((x) => !newIds.includes(x.id));
    
          let toUpdate = newValues.filter((x) => oldIds.includes(x.id));
    
          // Process to upsert
          model[key] = [];
          for (let elem of toDelete) {
            await elem.destroy();
          }
    
          for (let elem of toCreate) {
            model[key].push(await elem.constructor.create({ ...elem.dataValues, [model.constructor.name.toString() + "Id"]: model.id }));
          }
          for (let elem of toUpdate) {
            model[key].push(await elem.save());
          }
    
          // Update dataValues for serialization
          model.dataValues[key] = model[key];
        }
      }
      await model.save();
    
      return model;
    }

    It's probably not as flexible/complete as the other solution in this thread. But, as it's simpler, it can serve as a basis if someone wants to extend it :)

    Hi, can you explain on how to use your function, thx in advance, I've tried:

    let user = await User.findByPk(req.params.id, {include: Address});
    await user.set(req.body) // this includes array with addresses;
    user = await deepSave(user) //your function,
    await user.save(); //albeith your function does that

  13. n4an commented on Nov 18, 2021

    @n4an

    How to use it without that? The most important part is miss

  14. WikiRik commented on Dec 18, 2021

    @WikiRik
    Member

    @mittche I think your comment is missing some information. What are you referring to with 'it' and 'that'?

  15. nammon100x commented on Apr 4, 2022

    @nammon100x

    Has this been resolved?

  16. erlinis commented on Apr 29, 2022

    @erlinis

    This is a key feature, I need it !

  17. ephys commented on May 1, 2022

    @ephys
    Member

    Feel free to open a PR for it

  18. 4ybakut2004 commented on Oct 11, 2023

    @4ybakut2004

    Hi @papb , I'm a long time Ruby on Rails developer and therefore I have some input regarding this comment: #6808 (comment)

    ActiveRecord (RoR's ORM) goes by this rule of thumb:

    1. If the nested association parameters does not contain the primaryKey of that record, it will create a new record.
    2. If the nested association parameters contain the primaryKey of that record, it will update the record.
    3. If the nested association parameters contain both the primaryKey and the _destroy key has a truthy value, ActiveRecord will destroy the record.

    Again with JSON examples:

    Assuming all primary keys in this example are id.

    1. Create
    {
      id: 1,
      subcollection: [
        {
          attributeA: 'new value for attributeA' // There is no primary key in this object
        }
      ]
    }
    1. Update
    {
      id: 1,
      subcollection: [
        {
          id: 2,
          attributeA: 'new value for attributeA on subcollection id = 2' // The primary key is present in this case
        }
      ]
    }
    1. Destroy
    {
      id: 1,
      subcollection: [
        {
          id: 2,
          attributeA: 'new value for attributeA on subcollection id = 2' // This is ignored
          _destroy: true // Primary key is present and the _destroy key is both present and truthy
        }
      ]
    }

    Hope it gives some direction towards bringing this functionality to Sequelize.

    Hi! I'm currently switching from Ruby On Rails to NodeJS with sequelize. In sequelize without this feature i have to write a lot more code. This feature would be very useful for me too!

  19. added theissue type on Mar 9, 2025
  20. mustafa-patharia commented on Jul 15, 2026

    @mustafa-patharia

    I've had to solve this in my own projects, and the logic that's worked well for me is pretty close to the Rails approach @Nitemaeric described. Sharing it in case it helps settle the semantics, since that seems to be the actual blocker here.

    The idea: reuse the same include you already pass to create(), but on the update/save path too. Then for each record in the payload:

    • no primary key → create it and link it to the parent
    • primary key present → update it, and recurse into its own associations
    • primary key + _destroy: true → destroy it

    The one rule I'd really push for: if something isn't in the payload, leave it alone. A missing field stays as-is, a child that's not in the array stays as-is, and an empty array means "no change", not "delete everything". Nothing gets removed unless it's explicitly marked _destroy. That keeps partial updates safe — you should never wipe data just because it wasn't sent.

    Same rule for belongsToMany: add the links that are new, leave the ones you didn't send, and only detach a link when it's marked _destroy (detach the join row by default, destroying the target could be opt-in). It should also let you set the through-table columns inline, which most of the workarounds in this thread skip.

    Everything runs in one transaction (wrap one if the caller didn't pass one), and it should handle non-id primary keys and run the normal validations on the nested writes too.

    If this direction sounds right I'm happy to build it — starting with one association type (probably hasMany) so the PR stays reviewable, then extending. Mainly looking for a 👍 on the "absent = untouched, only _destroy removes" rule before I start, since everything builds on that. Open to discussion on the rest.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    hardstatus: in discussiontype: feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions