Waterline is an excellent ORM but I noticed that there are many features that are not present yet on waterline but Sequelize already have. So I have decided to switch to sequelize but still using Sails for the others things. I have search tutorial how to switch to sequelize but nothing. How can I replace Waterline for sequelize in sails Js?
The types of Object Relational Mappers with Node. js support are: Sequelize which has support for PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server databases.
Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.
Install Sequelize database driver for the database you would like to use by running one of the commands below. Install npm package Sequelize-CLI. Create a project folder. In your project folder path, run the command below to initialize Sequelize in the folder.
Sequelize is a promise-based Node. js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server.
I've moved forward with sequelize as well, there are two project that came out really recently, so i would like to announce them.
sails-hook-sequelize:
It follows the answer by Manuel Darveau, it will fetch all your models, import through sequelize and serves your models as a global variables, you can force the sequelize syncronization with the same way with migrate: 'drop'
sails-hook-sequelize-blueprints
Sails blueprints has saved me a LOT of time, so i've wrote a fork to work with sequelize, it work the same way than original blueprints, and you'll still have the same blueprints configurations such as rest
, shortcuts
, prefix
and so on, since waterline populate models with populateEach() function, it uses include: [{ all: true }]
which the result is the same.
A full example:
$ npm install sails-hook-sequelize
$ npm install sails-hook-sequelize-blueprints
$ npm install sequelize
$ npm install pg pg-hstore
$ npm install continuation-local-storage
.sailsrc
"hooks": {
"blueprints": false,
"orm": false,
"pubsub": false
}
connections.js
somePostgresqlServer: {
user: 'postgres',
password: '',
database: 'database',
dialect: 'postgres',
options: {
dialect: 'postgres',
host : 'localhost',
port : 5432,
logging: true
}
}
Your model definition
// user.js
module.exports = {
attributes: {
name: {
type: Sequelize.STRING,
allowNull: false
},
age: {
type: Sequelize.INTEGER
}
},
associations: function() {
user.hasMany(image, {
foreignKey: {
name: 'owner',
allowNull: false
}
});
},
options: {
tableName: 'user',
classMethods: {},
instanceMethods: {},
hooks: {}
}
};
That's it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With