Creating persistent instances
While an instance created with .build()
requires an explicit .save()
call to be stored in the database, .create()
omits that requirement altogether and automatically stores your instance's data once called.
Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => {
// you can now access the newly created task via the variable task
})
It is also possible to define which attributes can be set via the create method. This can be especially very handy if you create database entries based on a form which can be filled by a user. Using that would for example allow you to restrict the User
model to set only a username and an address but not an admin flag:
User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => {
// let's assume the default of isAdmin is false:
console.log(user.get({
plain: true
})) // => { username: 'barfooz', isAdmin: false }
})