In my Express app, I have to insert a new table record to MySQL database. I'm using Sequelize as the ORM. However, with the following setup , I couldn't do that. When I send a POST request to /users/register
method(UserController.signup()
is set to be executed at this route), it is waiting forever for a response in POSTman. I tried returning a string from UserController.signup()
and then the request was working fine.
Why can't I insert a record into database? Every help is highly appreciated.
UserController.js
var User = require('../models/user')
module.exports = {
signUp: (fname,email,password) => {
User.create({ firstName: fname, email: email, password: password }).then(user => {
console.log("New auto-generated ID:", user.id);
});
}
}
models/user.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
app.js
var createError = require('http-errors');
var express = require('express');
var db = require('./database')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var Router = require('./routes/index');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(Router);
db.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
app.use(function(req, res, next) {
next(createError(404));
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
});
module.exports = app;
database.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('test', 'root', '', {
host: 'localhost',
dialect: 'mariadb'
});
module.exports = sequelize
EDIT
I changed models/user.js
as follows.
'use strict';
var sequelize = require('../database')
var Sequelize = require('sequelize')
const User = sequelize.define('User', {
firstName: Sequelize.STRING,
email: Sequelize.STRING,
password: Sequelize.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
module.exports = User;
catch
and see what error you get. – Robert Niestrojmodels/User.js
as I've mentioned in the question under EDIT and it worked properly. But the User model I posted first is the one sequelize cli defined for me. How can I use that without error? – Pavindu