我尝试将数据插入数据库,但是当调用 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' });
我需要该查询只插入一个数据,而不是两次,有什么想法可以解决吗?