Skip to content

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

@andrewAtPaymentRails

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];

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bugDEPRECATED: replace with the "bug" issue type

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions