Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Sequelize.js

Other topics

Installation

Make sure that you first have Node.js and npm installed. Then install sequelize.js with npm

npm install --save sequelize

You will also need to install supported database Node.js modules. You only need to install the one you are using

For MYSQL and Mariadb

npm install --save mysql

For PostgreSQL

npm install --save pg pg-hstore

For SQLite

 npm install --save sqlite

For MSSQL

npm install --save tedious

Once you have you set up installed you can include and create a new Sequalize instance like so.

ES5 syntax

var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');

ES6 stage-0 Babel syntax

import Sequelize from 'sequelize';
const sequelize = new Sequelize('database', 'username', 'password');

You now have an instance of sequelize available. You could if you so feel inclined call it a different name such as

var db = new Sequelize('database', 'username', 'password');

or

var database = new Sequelize('database', 'username', 'password');

that part is your prerogative. Once you have this installed you can use it inside of your application as per the API documentation http://docs.sequelizejs.com/en/v3/api/sequelize/

Your next step after install would be to set up your own model

Defining Models

There are two ways to define models in sequelize; with sequelize.define(...), or sequelize.import(...). Both functions return a sequelize model object.

1. sequelize.define(modelName, attributes, [options])

This is the way to go if you'd like to define all your models in one file, or if you want to have extra control of your model definition.

/* Initialize Sequelize */
const config = {
    username: "database username",
    password: "database password",
    database: "database name",
    host: "database's host URL",
    dialect: "mysql" // Other options are postgres, sqlite, mariadb and mssql.
}
var Sequelize = require("sequelize");
var sequelize = new Sequelize(config);

/* Define Models */
sequelize.define("MyModel", {
    name: Sequelize.STRING,
    comment: Sequelize.TEXT,
    date: {
        type: Sequelize.DATE,
        allowNull: false
    }
});

For the documentation and more examples, check out the doclets documentation, or sequelize.com's documentation.


2. sequelize.import(path)

If your model definitions are broken into a file for each, then import is your friend. In the file where you initialize Sequelize, you need to call import like so:

/* Initialize Sequelize */
// Check previous code snippet for initialization

/* Define Models */
sequelize.import("./models/my_model.js"); // The path could be relative or absolute

Then in your model definition files, your code will look something like this:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define("MyModel", {
        name: DataTypes.STRING,
        comment: DataTypes.TEXT,
        date: {
            type: DataTypes.DATE,
            allowNull: false
        }
    });
};

For more information on how to use import, check out sequelize's express example on GitHub.

Contributors

Topic Id: 7705

Example Ids: 25299,28507

This site is not affiliated with any of the contributors.