w10D3 HW for Thursday - Using Sequelize Flashcards
what’s a model file?
a file that’ll be used by the application to query (search/question) the database. (basically like a file that does a fetch to the database)
- it’s used by the express application
- it’s part of the running software
what’s a migration file?
a file used to construct the database. It’s like a blueprint for what a table will look like.
- only used by sequelize cli tool to build the database
- it changes your db as your app grows
How are migration files different from model files?
Model files can be updated w/o having to remigrate and reseed our database.
Model files are usually used to change one row within a table in some way (ie. creating, reading, updating, deleting), while migrations are meant to build the table in the first place and seed files are meant to just add a bunch of rows at once.
How do seeder files interact with migration and model files?
They don’t directly.
Seeder files: keep them in mind when editing migration files.
- when making changes to migration files, be sure to unseed first!
- As long as you seed a table AFTER you migrate it (b/c you can’t add rows to a table that doesn’t exist) it’ll be fine.
What are seeder files?
Files where you input data
Why do we need a sequelize.close()?
This closes the connection to the database when done with it. we put it at the end of our promise.
ex. async function main() { ... } await sequelize.close(); }
main()
How do we save a new record with sequelize?
- we call the static build method on the Cat class (for ex.) with the desired values.
- we call the save method on the cat instance
what does .findByPk(1) do?
The findByPk method obtains only a single entry from the table, using the provided primary key. (in parenthesies)
Pk is primary key. 1 is the id of 1.
How do we read a record by primary key?
by using findByPk. be sure to use .close
How do we update a record?
.findByPk
update what you want
.save
.close
Be sure to save and close for the update to take effect!
How do we destroy a record?
by using .destroy
How can you make the create a one step process?
by calling the create class method:
in this example it 1) creates a cat instance and 2) saves the instance method
ex.
const { sequelize, Cat } = require(“./models”);
async function main() { const cat = await Cat.create({ firstName: "Curie", specialSkill: "jumping", age: 4, });
console.log(cat.toJSON());
await sequelize.close();
}
main();
What’s the one step method to delete?
use the destroy class method directly:
this example does 1) fetch the record and 2) destroy the instance method
const { sequelize, Cat } = require(“./models”);
async function main() { // Destroy the Cat record with id #3. await Cat.destroy({ where: { id: 3 } });
await sequelize.close();
}
main();
What does JSON.stringify do?
it turns JS into a JSON string
What does JSON.parse do?
it turns JSON into JS