You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
"options" is an object and non-compulsory argument
Find an entry by id.
Returns "null" if not found.
If found, the argument of callback in .then() contains the data.
Users.findById(id)
.then( (user)=>{ // null in 'user' if no entry found
console.log(user);
})
This small guide/text is written to just get the basic setup of sequelize up and running in a Express-based Node.Js setup".
For actual work with data and various advanced concepts, you will actually have to consult the official documentation.
Run command npm install --save sequelize mysql2 to install sequelize package and a dependency.
Create file "sequelize.js" .
We will import this file using "require" whenever we need to deal with tables & stuff.
--sequelize.js
This connects to the SQL DB with the specified parameters.
The DB should exist, tables will be created by this file automatically.
//Import Sequelize module
const Sequelize = require("sequelize");
//DB Configuration
const database = new Sequelize("database-name","username","password",{
dialect: "mysql",
host: "localhost"
});
//Test DB Connection
database.authenticate()
.then(()=>{
console.log("Successful connection to DB");
})
.catch((err)=>{
console.log("Connection Error: "+ err);
});
//Define table
const UserT = database.define("users or tableName",{
username: DataTypes.STRING,
password: DataTypes.STRING,
name: DataTypes.STRING,
});
//This actually creates table
UserT.sync();
//Create table & keep model definition separate file
const Users = database.import("./users.js");
Users.sync();
//Export table variables to use them in other files
module.exports = {
Users,UserT
};
--users.js
This file houses the definition for the user model.
In this way we can keep model definitions in separate files.