0

我尝试将数据插入数据库,但是当调用 de 端点时,数据被插入了两次。

我尝试使用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' });

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

4

1 回答 1

2

问题是:

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

正确的:

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

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

于 2019-09-09T18:24:24.260 回答