Sequelize is a NPM package with node operation MySQL, which contains many features: Database model mapping, transaction processing, model attribute checking, correlation mapping, etc., took two days to learn some basic operations, especially the associated mapping section of the operation, including 1:1, 1:n, N: Use the Express framework for simple rest services.
About the project structure:
Among them, routes store various routes, models configuration of various database model classes, Ref.js used to configure related Data Model association relationship, the main relationship is: User and Logininfo is 1:1, user and address is 1:n, user and role is N: n Relationships, the index.js is primarily load routing:
Module.exports = function (APP) { app.use ("/api/users", Require ("./user.js")); App.use ("/api/addresses", Require ("./address.js")); App.use ("/api/logininfos", Require ("./logininfo.js")); App.use ("/api/roles", Require ("./role.js");};
Ref.js Mapping Relationship Configuration class:
/** * Model Association class */var {Sequelize} = require (".. /config/db "), var User = Sequelize.import ("./user "), var logininfo = Sequelize.import ("./logininfo "), var Address = Sequelize.import ("./address"); var Role = Sequelize.import ("./role");//establish correlation between models User.hasone (Logininfo); Logininfo.belongsto (User); User.hasmany (Address, { foreignkey: ' user_id ', targetkey: ' id ', as : ' Addresses '//alias, the target model will be mixed into the source model and the name will be used , there are getaddresses, setaddresses and Other methods}); Address.belongsto (User); Address want to counter-check user must add this, otherwise can only implement user query Addressuser.belongstomany (Role, { through: "Userroles"}); Role.belongstomany (User, { through: ' Userroles '});//CREATE Table Sequelize.sync ({force:false});
Database Configuration class:
Const SEQUELIZE = require (' sequelize '); const SEQUELIZE = new Sequelize (' node-sequelize ', ' admin ', ' admin ', { host: ' L Ocalhost ', dialect: ' MySQL ', pool: { max:5, min:0, idle:10000 }});// Test database link sequelize.authenticate (). Then (function () { console.log ("database connection succeeded");}). catch (function (err) { ////database connection fails when print output console.error (err); throw err;}); Exports.sequelize = Sequelize;exports. Sequelize = sequelize;
Of course, the app.js to do is load the route, load the mapping relationship profile, and synchronize the data model with the database:
Load the primary foreign key relationship and create the database require ('./models/ref '); Router (APP);
Detailed code has been uploaded to Github:https://github.com/caiya/node-sequelize
Nodejs using sequelize to manipulate MySQL instances