Skip to content

Instantly share code, notes, and snippets.

@abhishekr700
Last active December 28, 2017 20:03
Show Gist options
  • Save abhishekr700/1c41bd00fb11d5993a1adac69b2c91d9 to your computer and use it in GitHub Desktop.
Save abhishekr700/1c41bd00fb11d5993a1adac69b2c91d9 to your computer and use it in GitHub Desktop.

Sequelize Querying Basics for newbies

Users = Table variable exported from sequelize

"options" object

=>"options" object is same for all find-like queries

Selective attributes =>

Users.findById(req.user.id,{
        attributes: ["id","username","name"]`
    })
        .then((user)=>{
            res.send(user);
        })

findById(id,options)

"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);
        })

Steps for Sequelize QuickStart

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.
module.exports = (database,DataTypes) => {
    return database.define("users",{
        username: DataTypes.STRING,
        password: DataTypes.STRING,
        name: DataTypes.STRING,
    })
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment