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

bulkCreate() now has a third argument which gives you the ability to validate each row before attempting to bulkInsert. #797

Merged
merged 2 commits into from
Aug 1, 2013

Conversation

durango
Copy link
Member

@durango durango commented Jul 31, 2013

bulkCreate was originally made to be a mainstream/fast way of inserting records, however, sometimes you want the luxury of being able to insert multiple rows at once without sacrificing model validations. I've added a third argument to bulkCreate which is an object and currently the only option is {validate: true} I actually need this for my workplace, so please do review the PR let me know what you don't like (if anything) etc.

The following code...

var Tasks = this.sequelize.define('Task', {
        name: {
          type: Sequelize.STRING,
          validate: {
            notNull: { args: true, msg: 'name cannot be null' }
          }
        },
        code: {
          type: Sequelize.STRING,
          validate: {
            len: [3, 10]
          }
        }
      })

      Tasks.sync({ force: true }).success(function() {
        Tasks.bulkCreate([
          {name: 'foo', code: '123'},
          {code: '1234'},
          {name: 'bar', code: '1'}
        ], null, {validate: true}).error(function(errors) {
          // console.log(errors)
        })
     })

Produces this errors object:

[
  {
    "record": {
      "code": "1234"
    },
    "errors": {
      "name": [
        "name cannot be null"
      ]
    }
  },
  {
    "record": {
      "name": "bar",
      "code": "1"
    },
    "errors": {
      "code": [
        "String is not in range: code"
      ]
    }
  }
]

Which would allow you to not only see the errors, but which records were the offenders.

durango added 2 commits July 30, 2013 23:39
…validate each row before attempting to bulkInsert.
…array', 'of', 'fields']} to .validate() which is useful for bulkCreate().
sdepold added a commit that referenced this pull request Aug 1, 2013
bulkCreate() now has a third argument which gives you the ability to validate each row before attempting to bulkInsert.
@sdepold sdepold merged commit 86c5564 into sequelize:master Aug 1, 2013
@durango durango deleted the bulk branch August 1, 2013 05:48
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

Successfully merging this pull request may close these issues.

2 participants