如何在Sequelize中插入数据

时间:2019-09-08 12:57:51

标签: express mariadb sequelize.js

在我的Express应用程序中,我必须向MySQL数据库插入一个新的表记录。我正在使用Sequelize作为ORM。但是,使用以下设置,我无法做到这一点。当我向/users/register方法发送POST请求(将UserController.signup()设置为在此路由上执行)时,它将永远等待POSTman中的响应。我尝试从UserController.signup()返回一个字符串,然后请求运行正常。

为什么不能将记录插入数据库?我们非常感谢您的帮助。

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

编辑

我如下更改了models/user.js

'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;

1 个答案:

答案 0 :(得分:0)

向您的用户模型添加id属性。您正在尝试从User模型访问值,但未声明。它仍然会为您自动生成。尝试这样的事情:

模型user.js

const User = sequelize.define('User', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    firstName: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
}, {});

迁移 migration:generate --name createUser

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      firstName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      password: {
        type: Sequelize.STRING
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }