Answer the question
In order to leave comments, you need to log in
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);
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'
});
}
}
sequelize = new Sequelize('mysql://[email protected]/nodejs');
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) 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?
global.varName = 'hello world';
// 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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question