Skip to content
Share
Explore

Data Types


// model.js
// get data type from Sequelize package
const Sequelize = require('sequelize');

// import connection from helpers
const sequelize = require('../helpers/database');

// Article Model
const Article = sequelize.define('article', {
id: {
type: Sequelize.INTEGER, // define type from Sequelize package
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: {
type: Sequelize.STRING,
allowNull: false
},
slug: {
type: Sequelize.STRING,
allowNull: false
},
content: {
type: Sequelize.TEXT,
allowNull: false
},
featuredImage: {
type: Sequelize.STRING,
allowNull: true
},
status: {
type: Sequelize.STRING,
allowNull: false
}
});

module.exports = Article;
// controller.js

// insert into database
Article.create()

// find all (no need to re-write static fn within the model
Article.findAll()

// find by Id, primary key
Article.findByPk()
const article = await Article.findOne({ where: { id } });
const article = await Article.findOne({ where: { id: uuid } });

// find all & custom
const article = await Article.findAll({ where: { id: uuid } });

// update
// get existing article
const existingArticle = await Article.findByPk(articleId);

// if article exists
if (existingArticle) {
existingArticle.title = title;
existingArticle.content = content;
existingArticle.featuredImage = featuredImage;
// do not change slug, or status or id
// save updated article (with Sequelize instance method)
await existingArticle.save();
console.log('Article saved: ', existingArticle.title);
res.redirect('/list');
}

// delete
// find article by id
articleToDelete = await Article.findByPk(articleId);

if (articleToDelete) {
articleToDelete.destroy();
console.log('Article deleted: ', articleToDelete.title);
res.redirect('/list');
}
All WHERE conditions here:

Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.