Sequelize Seed Error: Cannot Read Property 'proxies' of Undefined
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction back up, relations, eager and lazy loading, read replication and more.
An ORM library is a completely ordinary library written in your language of selection that encapsulates the code needed to dispense the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using -stackoverflow
Though Sequelize supports several other database clients, this article focuses on using Sequelize with Postgres. We volition be building a simple weblog where users can create posts, view posts and add comments to a post.
This commodity is divided into ii parts:
- Role One - Sequelize setup, configuration, migration and seeding.
- Function Ii - Performing Grime with Sequelize.
Requirements
- NodeJs installed
- npm or yarn installed
Office One
If you lot have non created an express project, quickly do so and open the project in a last. At the root folder of the project, run the post-obit commands to install the necessary dependencies:
npm install sequelize sequelize-cli pg pg-hstore
A brief caption of the libraries installed in the command above:
sequelize is the sequelize library itself.
sequelize-cli is a bundle that enables us interact with the database through sequelize
from the CLI.
pg short for postgres is a Postgres client for Node.js
pg-hstore is a node bundle for serializing and deserializing JSON data to hstore format.
Side by side up, let'south create sequelize config, to do that, run command below to create a file called .sequelizerc
bear on .sequelizerc
Re-create the lawmaking beneath into the .seqluelizerc
file:
const path = require ( ' path ' ) module . exports = { config : path . resolve ( ' ./database/config ' , ' config.js ' ), ' models-path ' : path . resolve ( ' ./database/models ' ), ' seeders-path ' : path . resolve ( ' ./database/seeders ' ), ' migrations-path ' : path . resolve ( ' ./database/migrations ' ), }
Sequelize uses the .sequelizerc
file to generate the config and the model using the specified path.
Next up, we generate the config past running the command below:
sequelize init
Now, you should accept a new directory called database
with a scaffolding as shown below:
Next upward, permit's edit the database/config/config.js
.
Supercede the content of the database/config/config.js
with the code below:
require ( ' dotenv ' ). config () module . exports = { development : { url : process . env . DEV_DATABASE_URL , dialect : ' postgres ' , }, test : { url : process . env . TEST_DATABASE_URL , dialect : ' postgres ' , }, production : { url : procedure . env . DATABASE_URL , dialect : ' postgres ' , }, }
Since our focus is on using Sequelize with Postgres, we've streamlined the config to be Postgres specific.
Since we are using Postgres, we'll be using connectedness string to connect to the database. Create two Postgres databases i for development and i for test (if you lot need test for your project).
How to create a Postgres database connection string
Yous can leap to the next function if you've already created database.
Method 1
If you have Postgres installed locally follow the steps beneath to create a database and generate connection string. Open a terminal and run the command below:
createdb dev_db -U <db_user> createdb test_db -U <db_user>
The connection strings for the databases above will be:
postgres://<db_user>:<db_password>@127.0.0.1:5432/dev_db postgres://<db_user>:<db_password>@127.0.0.ane:5432/test_db
Now, create a .env
file and copy the snippet below into it.
DATABASE_URL= DEV_DATABASE_URL=postgres://<db_user>:<db_password>@127.0.0.1:5432/dev_db TEST_DATABASE_URL=postgres://<db_user>:<db_password>@127.0.0.1:5432/test_db
Note that if you're using Heroku for production, Heroku will generate a connection string and inject into the environment variable DATABASE_URL
in one case you add the Postgres improver.
Method 2
If y'all don't have Postgres installed locally, you lot tin make use of ElephantSQL to create the databases.
Creating Models and Migrations
We demand to create the User, Mail and Comment models. To do that run the post-obit commands:
sequelize model:generate --name User --attributes name:string,e-mail:string sequelize model:generate --name Postal service --attributes title:string,content:text,userId:integer sequelize model:generate --name Annotate --attributes postId:integer,comment:text,userId:integer
Each of the commands in a higher place will generate a migration and a model in /database/migrations
and database/models
directory respectively.
Note, ensure there's no space betwixt --attributes
definition.
For case, --attributes postId:integer, comment:text, userId:integer
will throw an fault ERROR: Aspect '' cannot exist parsed: Cannot read property 'dataType' of undefined
because of the whitespace betwixt attributes.
Adjacent up, nosotros need to make a few changes on the migrations and models.
Starting time nosotros need to add NOT NULL
constraints to the FOREIGN_KEY
attributes (userId, postId). The outset fourth dimension I worked with Sequelize, I didn't know well-nigh this and the model eager loading wasn't working. In the migrations edit the FOREIGN_KEY
attributes every bit shown beneath:
userId : { type : Sequelize . INTEGER , allowNull : imitation , }, postId : { type : Sequelize . INTEGER , allowNull : false , },
Edit the models/index.js
file equally follows:
const fs = require ( ' fs ' ); const path = require ( ' path ' ); const Sequelize = crave ( ' sequelize ' ); const envConfigs = require ( ' ../config/config ' ); const basename = path . basename ( __filename ); const env = process . env . NODE_ENV || ' development ' ; const config = envConfigs [ env ]; const db = {}; let sequelize ; if ( config . url ) { sequelize = new Sequelize ( config . url , config ); } else { sequelize = new Sequelize ( config . database , config . username , config . password , config ); } fs . readdirSync ( __dirname ) . filter ( file => { return ( file . indexOf ( ' . ' ) !== 0 ) && ( file !== basename ) && ( file . piece ( - 3 ) === ' .js ' ); }) . forEach ( file => { const model = sequelize [ ' import ' ]( path . join ( __dirname , file )); db [ model . proper name ] = model ; }); Object . keys ( db ). forEach ( modelName => { if ( db [ modelName ]. associate ) { db [ modelName ]. acquaintance ( db ); } }); db . sequelize = sequelize ; db . Sequelize = Sequelize ; module . exports = db ; //models/alphabetize.js
Defining the model relationships
We have three models that are interrelated as follows
- a user has many posts and a post belongs to a user (1:n)
- a user has many comments and a comment belongs to a user (1:northward)
- a post has many comments and a comment belongs to a mail (one:n)
To attain institute the relationships above programmatically, allow'due south edit the models as follows:
module . exports = ( sequelize , DataTypes ) => { const User = sequelize . ascertain ( ' User ' , { name : DataTypes . STRING , electronic mail : DataTypes . STRING }, {}); User . acquaintance = part ( models ) { // associations tin can be defined here User . hasMany ( models . Mail service , { foreignKey : ' userId ' , as : ' posts ' , onDelete : ' CASCADE ' , }); User . hasMany ( models . Annotate , { foreignKey : ' userId ' , every bit : ' comments ' , onDelete : ' Cascade ' , }); }; render User ; }; // database/models/user.js
module . exports = ( sequelize , DataTypes ) => { const Post = sequelize . ascertain ( ' Post ' , { title : DataTypes . STRING , content : DataTypes . TEXT , userId : DataTypes . INTEGER }, {}); Postal service . associate = office ( models ) { // associations tin can exist divers hither Post . hasMany ( models . Comment , { foreignKey : ' postId ' , as : ' comments ' , onDelete : ' CASCADE ' , }); Mail . belongsTo ( models . User , { foreignKey : ' userId ' , every bit : ' writer ' , onDelete : ' CASCADE ' , }) }; render Post ; }; // database/models/postal service.js
module . exports = ( sequelize , DataTypes ) => { const Comment = sequelize . define ( ' Comment ' , { postId : DataTypes . INTEGER , comment : DataTypes . TEXT , userId : DataTypes . INTEGER }, {}); Annotate . associate = function ( models ) { // associations can be defined here Comment . belongsTo ( models . User , { foreignKey : ' userId ' , equally : ' author ' }); Comment . belongsTo ( models . Post , { foreignKey : ' postId ' , as : ' post ' }); }; return Comment ; }; // database/models/comment.js
It's fourth dimension to run the migrations which will interpret the migrations into tables in the database. Run
sequelize db:migrate
If everything went well, the tables would exist generated and nosotros are ready to start shoving data into the database.
Seeding data to the database
Let'southward populate the database with some dummy information. Run the commands below to generate the seed files for the models.
sequelize seed:generate --name User sequelize seed:generate --name Postal service sequelize seed:generate --name Comment
The commands above volition generate three files xxxx-User.js
, xxxx-Post.js
, and xxxx-Annotate.js
for User
, Post
and Comment
models respectively.
Edit the seed files equally follows:
module . exports = { up : ( queryInterface , Sequelize ) => queryInterface . bulkInsert ( ' Users ' , [ { proper noun : ' Jane Doe ' , e-mail : ' janedoe@example.com ' , createdAt : new Date (), updatedAt : new Date (), }, { name : ' Jon Doe ' , email : ' jondoe@example.com ' , createdAt : new Engagement (), updatedAt : new Appointment (), }, ], {}, ), downwards : ( queryInterface , Sequelize ) => queryInterface . bulkDelete ( ' Users ' , nil , {}), }; // database/seeds/xxxx-User.js
module . exports = { upwards : ( queryInterface , Sequelize ) => queryInterface . bulkInsert ( " Posts " , [ { userId : 1 , title : " hispotan de nu " , content : " Nulla mollis molestie lorem. Quisque ut erat. Curabitur gravida nisi at nibh. " , createdAt : new Date (), updatedAt : new Date () }, { userId : 2 , title : ' some dummy title ' , content : " Maecenas tincidunt lacus at velit. Vivamus vel nulla eget eros elementum pellentesque. Quisque porta volutpat erat. " , createdAt : new Engagement (), updatedAt : new Engagement () } ], {} ), down : ( queryInterface , Sequelize ) => queryInterface . bulkDelete ( " Posts " , nil , {}) }; // database/seeds/xxxx-Post.js
module . exports = { upwards : ( queryInterface , Sequelize ) => queryInterface . bulkInsert ( " Comments " , [ { userId : 1 , postId : 2 , annotate : " Nulla mollis molestie lorem. Quisque ut erat. Curabitur gravida nisi at nibh. " , createdAt : new Date (), updatedAt : new Engagement () }, { userId : 2 , postId : 1 , annotate : " Maecenas tincidunt lacus at velit. Vivamus vel nulla eget eros elementum pellentesque. Quisque porta volutpat erat. " , createdAt : new Date (), updatedAt : new Date () } ], {} ), down : ( queryInterface , Sequelize ) => queryInterface . bulkDelete ( " Comments " , null , {}) }; // database/seeds/xxxx-Comment.js
Now, run the command below to seed the database:
sequelize db:seed:all
You lot can clone the complete lawmaking for this article here
Yo! that is information technology for now. In the office two of this article, I will be building on this article to implement Grime for the web log. Stay tuned! 📌
Suggested resources
- Sequelize Docs
- What is an ORM and Why You Should Utilize it
This commodity was originally published on my blog
Source: https://dev.to/nedsoft/getting-started-with-sequelize-and-postgres-emp
Belum ada Komentar untuk "Sequelize Seed Error: Cannot Read Property 'proxies' of Undefined"
Posting Komentar