Using Models
Just like using express and the other modules, your models must be required in order to access them in your app.
CRUD with Sequelize (Using our User model)
Create
Read One
What happens if you include a where
clause that doesn't match any rows of data? Try it!
Find or Create
The method findOrCreate can be used to check if a certain element is already existing in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created with the provided attributes (a combination of where
and defaults
)
Find All
findAll returns more than one instance, which is useful if you need more than one record. find only returns one record.
Update
See this stack overflow for more on what the promise returns.
Delete (destroy)
Promises
After a sequelize statement, we can interact with the return of that object using .then
.
Finding a user
In a findOrCreate
, a callback will return back an array, instead of a single object. The array parameter syntax shown below is the sequelize 5 syntax that mimics the old .spread()
operator
Sequelize Promises
The main callback handlers to be used are as follows.
.then
- default promise called when a query is completed..catch
- triggered if something goes wrong (an error)..finally
- triggered after all other callbacks. Can be used for cleanup.
The important thing to remember is that all queries take time and are asynchronous, so you MUST use promises to execute code that needs to happen after the query is completed.
Last updated