Skip to content

bulkUpdate() will crash if there's a "field: " definition and a custom setter with validation #9796

Closed

Description

@andrewAtPaymentRails

What are you doing?

I have a definition similar to this ->

      const user = this.sequelize.define('Users', {
        username: {
          type: Sequelize.STRING,
          allowNull: false,
          field: "data", // something different
          get: function() {
            const val = this.getDataValue("username");
            return val.substring(0, val.length - 1);
          },
          set: function(val) {
            if(val.indexOf('!') > -1) {
              throw new Error("val should not include a '!'");
            }
            this.setDataValue("username", val + "!");
          }
        }
      });
      const data = [{ username: "jon" }];
      return user.bulkCreate(data).then(() => {
        return user.findAll().then(users1 => {
          expect(users1[0].username).to.equal('jon');
        });
      });

What do you expect to happen?

I expect it to work

What is actually happening?

but it throw an exception: "val should not include a '!'"

Analysis

The problem seems to be in Model.js where bulkCreate(), when creating a result object to return, does this:

        for (const attr in this.rawAttributes) {
          if (this.rawAttributes[attr].field &&
              instance.dataValues[this.rawAttributes[attr].field] !== undefined &&
              this.rawAttributes[attr].field !== attr
          ) {
            instance.set(attr, instance.dataValues[this.rawAttributes[attr].field]);
            delete instance.dataValues[this.rawAttributes[attr].field];
          }
          instance._previousDataValues[attr] = instance.dataValues[attr];
          instance.changed(attr, false);
        }
        instance.isNewRecord = false;

Note the instance.set(attr, instance.dataValues[this.rawAttributes[attr].field]);

It should be something like

instance.dataValues[attr] = instance.dataValues[this.rawAttributes[attr].field];

Activity

  1. andrewAtPaymentRails commented on Aug 13, 2018

    @andrewAtPaymentRails
    ContributorAuthor

    I have a patch for this

  2. sushantdhiman commented on Aug 15, 2018

    @sushantdhiman
    Contributor

    Fixed by #9797

  3. added
    type: bug
    on Aug 15, 2018
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

    type: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions