Equivalence of Rails console for Node.js

后端 未结 5 471
梦如初夏
梦如初夏 2021-02-03 18:26

I am trying out Node.js Express framework, and looking for plugin that allows me to interact with my models via console, similar to Rails console. Is there such a thing in NodeJ

5条回答
  •  孤城傲影
    2021-02-03 19:03

    Here is the way to do it, with SQL databases:

    Install and use Sequelize, it is Node's ORM answer to Active Record in Rails. It even has a CLI for scaffolding models and migrations.

    node --experimental-repl-await

    > models = require('./models'); 
    > User = models.User; //however you load the model in your actual app this may vary
    > await User.findAll(); //use await, then any sequelize calls here
    

    TLDR

    This gives you access to all of the models just as you would in Rails active record. Sequelize takes a bit of getting used to, but in many ways it is actually more flexible than Active Record while still having the same features.

    Sequelize uses promises, so to run these properly in REPL you will want to use the --experimental-repl-await flag when running node. Otherwise, you can get bluebird promise errors

    If you don't want to type out the require('./models') step, you can use console.js - a setup file for REPL at the root of your directory - to preload this. However, I find it easier to just type this one line out in REPL

提交回复
热议问题