W
W
WebDev2015-10-26 10:58:28
Node.js
WebDev, 2015-10-26 10:58:28

Sequilize NodeJS?

Hello, I'm learning nodejs, 3 questions:
1) Do they use sequilize orm in nodejs? There are a lot of modules, tell me what they use?
2) How to correctly declare variables globally in node.js? I have organized a kind of MVC, there are controllers, models and views. This is how it looks like:
In app.js

var products = require(__dirname + '/controllers/products');
app.get('/product', products.index);
app.get('/product/add', products.add);
app.get('/product/edit', products.edit);

And the controller looks like this:
module.exports = {
    index : function(req, res) {
        res.render('products/index', {
            'title' : 'Products list'
        });
    },
    add : function(req, res) {
        res.render('products/add', {
            'title' : 'Add product'
        });
    },
    edit : function(req, res) {
        res.render('products/edit', {
            'title' : 'Edit product'
        });
    }
}

Actually the question is: How can I use the database connection object in the controller? Now I declared it globally in app.js
sequelize = new Sequelize('mysql://[email protected]/nodejs');

But is there perhaps a more beautiful approach?
3) With this MVC structure, you have to manually connect all controllers and models. Is it possible to automate somehow (similar to __autoload() in PHP)?
UPD: One more question: am I getting the results from the database through the callback correctly?
product.findAll().then(function(prods) {
            var products = [];
            prods.forEach(function(prod) {
                products.push(prod);
            });

            res.render('products/index', {
                'title'     : 'Products list',
                'products'  : products
            });
        });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2015-10-26
@kirill-93

1) Do they use sequilize orm in nodejs? There are a lot of modules, tell me what they use?
Some people use it, some don't. People are different, projects are also different. I use it in one project and not in another. What is the real question?
Like this: global.varName = 'hello world';
But in general it's not very neat. Global variables are evil. Here's how it's done for me (ES6):
// dbConnect.js
'use strict';

const Sequelize = require('sequelize');
const settings = require('./settings');
const connection = new Sequelize(settings.db);

const modelNames = ['Order', 'User'];

for (const modelName of modelNames) {
    connection.import(`./models/${modelName}.js`);
}

for (const modelName of Object.keys(connection.models)) {
    if ('associate' in connection.models[modelName]) {
        connection.models[modelName].associate(connection.models);
    }
}

module.exports = connection;

// models/User.js
'use strict';

const generatePassword = require('password-generator');

module.exports = (sequelize, DataTypes) => {
    let User;

    const schema = {
        username: {type: DataTypes.STRING, validate: {isEmail: true}},
        password: DataTypes.STRING
    };

    const options = {
        paranoid: true,
        classMethods: {
            authOrCreate (username, done) {
                const query = {
                    where: {
                        username
                    },
                    defaults: {
                        password: generatePassword()
                    }
                };
                this.findOrCreate(query).spread((user, created) => {
                    if (created) {
                        done(null, user);
                    } else {
                        done(null, user);
                    }
                }, (err) => {
                    done(err);
                });
            },

            associate (models) {
                User.hasMany(models.Order);
            }
        }
    };

    User = sequelize.define('User', schema, options);

    return User;
};

// где-то в контроллере
const Orders = require('../../dbConnection').models.Orders;

The fact is that commonjs modules are cached, and are executed only at the time of the first call, then the result is simply returned again and again. So all you need to do is require('./path/to/dbConnect') from anywhere, and voila, there you have it.
Implicit dependencies are evil. Firstly, it is more difficult to understand later / to another person what depends on what and where it can break. Secondly, it is more difficult to control whether this module has grown too large. Third, explicit is better than implicit. It's like global variables, only implicit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question