Use the Sequelize ORM to access a PostgreSQL databases Module#61 Flashcards
How can we install the sequelize package via npm
First run npm init -y
npm install sequelize
What is the first step in using sequelize?
First make a connection to the DB as follows, update the default fields;
const user = '' const host = 'localhost' const database = '' const password = '' const port = ''
When you specify “dialect” what are you telling Sequelize?
On this line we’re telling Sequelize what kind of database to expect.
What is the syntax for creating a new Sequelize object instance?
const sequelize = new Sequelize(database, user, password, { host, port, dialect: 'postgres', logging: false })
What do you need to do in order to manipulate a table
You need to create a model
How can we get data out of the table?
Use the .findAll( ) method
Dog.findAll()
When using the findAll( ) method it will return a list of rows. How can we access them?
Assign it to a variable called results: const results = await Dog.findAll( )
How can we limit the columns we retrieve?
By passing an object with the attributes array:
Dog.findAll({
attributes: [‘age’]
})
What if you want to narrow the results even more, for example all dogs aged *
Add a WHERE clause, with your age parameter:
Dog.findAll({ where: { age: 8, } })
To get all dogs equal or higher to 5?
Use Op.gte
Dog.findAll({ where: { age: { [Op.gte]: 5, } } })
How is new data entered into our DB?
Using the .create( ) method
How do we update the data we already have?
Surprise! Using the .update( ) method. But it needs to get attached to the proper object you want to update.
Example:
Dog.update({ age: 9 }, { where: { name: 'Roger' } })
What happens when we remove the where property?
It will update all rows instead of just a single row.