为什么 sequelize 插入两次?

Why sequelize insert twice?

我尝试向数据库中插入数据,但是在调用 de endpoint 时,数据被插入了两次。

我尝试用async await,在函数外调用model,用promise,问题没有解决

插入:

exports.create = (req, res) => {
  let User = require('./models').User;

  User.create({
    id: 0,
    name: 'Jon',
    age: 21,
    email: 'test@gameil.com',
    city: 1
  })
  .then(result => {
    res.send(result);
  })
  .catch(error => {
    res.status(500).send(error);
  })
}

型号索引:

'use strict';

const fs        = require('fs');
const path      = require('path');
const Sequelize = require('sequelize');
const basename  = path.basename(__filename);

//PRINCIPAL DATABASE CONFIG
const env = process.env.NODE_ENV || 'main';
const config = require(__dirname + '/../../configs/v1/config.json')[env];
const db = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');//open .js file
  })
  .forEach(file => {
    var model = sequelize['import'](path.join(__dirname, file));//connect data base using file model
    db[model.name] = model;//model.name example (const model = require(./model).modelName;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

型号:

module.exports = function (sequelize, DataTypes) {
    let Users= sequelize.define('Users', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true
        },
        name: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        age:{
            type: DataTypes.INTEGER(11),
            allowNull: false
        },
        email:{
            type: DataTypes.STRING(256),
            allowNull: false
        },
        city:{
            type: DataTypes.INTEGER(11),
            allowNull: false
        },
  }, {
    tableName: 'users',
    timestamps: true,
    paranoid: true
  });
  Users.associate = function (models) {
        Users.belongsTo(models.Cities, { foreignKey: 'city' });
  }
  return Users;
};

路线:

const controller = require('../controllers/userController');

module.exports = (router, opts, done)=>{
    router.post('/', controller.create);
    done();
}

应用程序:

const users = require('./routes/users');

app.register(users, { prefix: '/user' });

我需要该查询只插入一个数据,而不是两次,有解决办法吗?

问题是:

addHook('prehandler', async(req, res, done)=>{
  done();//its wrong because use async/await
});

正确:

addHook('prehandler', async(req, res)=>{
  return
});

使用 async/await 或返回 Promise 时,done 回调不可用。如果您在这种情况下调用完成回调,可能会发生意外行为,例如重复调用处理程序。