Rails ActiveRecord Migrations similar in Node/ExpressJs

Viewed 1359

I am from Ruby world, started learning Express js, Is there a Rails ActiveRecord Migrations kind of library in Node/ExpressJs ?

4 Answers

I am Ruby on Rails developer, and I was searching for similar framework on Node.js.

Now I am using Sails.js with Waterline, used PostgreSQL, with migrations library.
File structure is almost the same as in Rails. Almost the same as with ActiveRecord. I am very happy with my current setup, works perfect and blazing fast.

I have 500 functional tests. Each test has many queries, runs trough 10-20 clases with many update, create, find queries. With Rails and PG database they would run in 10 minutes. With Sails and PG database they did run in 2 minutes(or more - i had this setup). With Sails and MongoDB(i have just migrated from pg to mongo) the same tests runs in 12 seconds!

And I still have the Rails-like file system and Waterline, which is similar to ActiveRecord. All transactions I have moved to Redis(that was hard, but did the job).

I think you can use Sequelize, which is really inspired of ActiveRecord. Maybe you'll need to use the package Migrat too, which look like a really good migration tool

I think you should use Sequelize, the syntax is very simple and the curve learn is fast. Here are same samples of how to define Model in sequelize:

const User = sequelize.define('user', {
  username: { type: Sequelize.STRING, allowNull: false },
  password: { type: Sequelize.STRING, allowNull: false },
  admin: { type: Sequelize.BOOLEAN, defaultValue: false }
});

After you call on your code the sync() method Sequelize will CREATE TABLE IF NOT EXISTS all your models adding id (that you could change too), created_at and updated_at (timestamps) and you can make calls like that:

sequelize.sync()
  .then(() => User.create({
    username: 'administrator',
    password: 'yahoo',
    admin: true
  }))
  .then(userCreated => {
    console.log(userCreated.toJSON());
  });

You can make a very complex queries with little code and mix them with express.js to response to your clients, for example:

User.findAll({
  where: {
    [Op.iLike] : { username: 'Jack%' },
    admin: true
  }
 }).then(usersList => {
   if (!usersList) { 
     response.status(404).json({ error: 'not found' }); 
     return null; 
   }

   for (var i = 0; i < usersList.length; i++) {
    usersList[I].something = 42;
   }

   response.json(usersList);

   return null;
 });

This will produce something like: SELECT "id", "username", "password", "admin", "created_at", "updated_at" WHERE "admin" = true AND "username" ILIKE 'Jack%';

Related