Building a non-persistent instance

In order to create instances of defined classes just do as follows. You might recognize the syntax if you coded Ruby in the past. Using the build-method will return an unsaved object, which you explicitly have to save.

  1. const project = Project.build({
  2. title: 'my awesome project',
  3. description: 'woot woot. this will make me a rich man'
  4. })
  5. const task = Task.build({
  6. title: 'specify the project idea',
  7. description: 'bla',
  8. deadline: new Date()
  9. })

Built instances will automatically get default values when they were defined:

  1. // first define the model
  2. class Task extends Model {}
  3. Task.init({
  4. title: Sequelize.STRING,
  5. rating: { type: Sequelize.TINYINT, defaultValue: 3 }
  6. }, { sequelize, modelName: 'task' });
  7. // now instantiate an object
  8. const task = Task.build({title: 'very important task'})
  9. task.title // ==> 'very important task'
  10. task.rating // ==> 3

To get it stored in the database, use the save-method and catch the events … if needed:

  1. project.save().then(() => {
  2. // my nice callback stuff
  3. })
  4. task.save().catch(error => {
  5. // mhhh, wth!
  6. })
  7. // you can also build, save and access the object with chaining:
  8. Task
  9. .build({ title: 'foo', description: 'bar', deadline: new Date() })
  10. .save()
  11. .then(anotherTask => {
  12. // you can now access the currently saved task with the variable anotherTask... nice!
  13. })
  14. .catch(error => {
  15. // Ooops, do some error-handling
  16. })