我的node.js
api
使用sequelize.js
时出现问题。
在特定的端点,我试图在一个表中插入一行,似乎一切正常但是
一段时间(1小时-24小时后),当我试图创建行时,我收到错误:
错误:ER_NO_DEFAULT_FOR_FIELD:字段' user_id'没有默认值
原因是生成的查询尝试插入空值
insert into company_users (user_id,company_id)values()
。
我检查了我试图插入断点的数据,一切都很好。
如果我重新启动api
所有似乎都工作正常,但几个小时后再次出现相同的问题。我想提一下,问题只出现在这个端点,此端点也创建用户,添加用户分支,添加用户设置,adduser角色,最后在公司用户处添加用户。
router.post('/Users',jsonParser, function(req,res,next){
var newData = req.body;
if(newData.username){
newData.username=null;
}
if(newData.password||newData.password!==""){
newData.password = crypto.createHash('md5').update(newData.password).digest('hex');
}else{
delete newData.password;
}
models[req.domainURL].sequelize.transaction(function (t) {
var created_userID;
return DB.createUser(req.domainURL, newData).then(function(results){
created_userID=results.ID;
var userbranchIds=newData.branchIDs.map(function(branchID){
var userbranch={
userID:created_userID,
branchID:branchID
};
return userbranch;
});
return DB.addUserBranches(req.domainURL,userbranchIds);
}).then(function(results){
var usersettings = newData.userSettings.map(function(userSetting){
var usersetting={
settingID : userSetting.settingID,
settingValue: userSetting.value,
userID:created_userID
};
return usersetting;
});
return DB.addUserUserSettings(req.domainURL,usersettings);
}).then(function(results){
return DB.addUserRole(req.domainURL,newData.RoleId,created_userID);
}).then(function(results){
///here there is the problem
return DB.addCompanyUser(req.domainURL,req.decoded.companyId,created_userID);
});
}).then(function(results){
res.send();
}).catch(function(error){
Errors.handleError(new Errors.SequelizeErrorWrapper(error,'User'),res);
});
});
var CompanyUsers = sequelize.define('CompanyUsers',{
companyID:
{
type: DataTypes.INTEGER(10).UNSIGNED, primaryKey: true, allowNull: false, field: 'company_id'
},
userID:
{
type: DataTypes.INTEGER(10).UNSIGNED, primaryKey: true, allowNull: false, field: 'user_id'
}
},
{
classMethods: {
associate: function(models) {
CompanyUsers.belongsTo(models.Companies, {foreignKey: 'companyID', targetKey: 'ID'});
CompanyUsers.belongsTo(models.Users, {foreignKey: 'userID', targetKey: 'ID'});
}
},
timestamps:false,
tableName: 'company_users',
freezeTableName: true
});
};
addCompanyUser: function(domain,company_id,created_user_id){
var data={
companyID:company_id,
userID:created_user_id
};
return models[domain].CompanyUsers.create(data);
}