Skip to content

Instantly share code, notes, and snippets.

@yun-sangho
Created March 6, 2019 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yun-sangho/ba7ab9b88211d1cea4ee199d69b58f6d to your computer and use it in GitHub Desktop.
Save yun-sangho/ba7ab9b88211d1cea4ee199d69b58f6d to your computer and use it in GitHub Desktop.
ORM-Example
/* You'll need to
* npm install sequelize
* before running this example. Documentation is at http://sequelizejs.com/
*/
var Sequelize = require('sequelize');
var db = new Sequelize('chatter', 'root', '');
/* TODO this constructor takes the database name, username, then password.
* Modify the arguments if you need to */
/* first define the data structure by giving property names and datatypes
* See http://sequelizejs.com for other datatypes you can use besides STRING. */
var User = db.define('User', {
username: Sequelize.STRING
});
var Message = db.define('Message', {
userid: Sequelize.INTEGER,
text: Sequelize.STRING,
roomname: Sequelize.STRING
});
/* Sequelize comes with built in support for promises
* making it easy to chain asynchronous operations together */
User.sync()
.then(function() {
// Now instantiate an object and save it:
return User.create({username: 'Jean Valjean'});
})
.then(function() {
// Retrieve objects from the database:
return User.findAll({ where: {username: 'Jean Valjean'} });
})
.then(function(users) {
users.forEach(function(user) {
console.log(user.username + ' exists');
});
db.close();
})
.catch(function(err) {
// Handle any error in the chain
console.error(err);
db.close();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment