我正在开发一个项目,管理员可以在其中添加聊天室,其中有五个字段:(id,创建者(创建者的管理员),名称,slug和createdAt)我收到此错误未处理拒绝SequelizeValidationError :notNull Violation:name不能为null 。
//models/user.js
var Sequelize = require('sequelize');
var passportLocalSequelize = require('passport-local-sequelize');
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var mydb = new Sequelize(config.database, config.username, config.password, config);
// We do not need additional features for our users, so we just use the default user model
// provided by Passport
var User = passportLocalSequelize.defineUser(mydb,
{
email: { type: Sequelize.STRING, allowNull: false, unique: true }
},{}
);
//Function at a prototype level for performance optimization
User.Instance.prototype.$Model.findByEmail = function(email, done){
var parameters = {};
parameters.email = email;
var user = this.findOne({where: parameters});
user.then(function(usr) {
done(null, usr);
});
}
mydb.authenticate().then(function(done)
{
if(mydb.sync({force: false}))
done();
}).catch(function(error,user)
{
console.log(error);
});
module.exports = User;
//models/chat.js
var Sequelize = require('sequelize');
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var User = require('./user');
var mydb = new Sequelize(config.database, config.username, config.password, config);
var Chat = mydb.define('Chat',
{
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: Sequelize.STRING, unique: true, allowNull: false,
validate: {
notNull: { args: true, msg: "You must enter a name" }
},
set: function(val) {
val = val.toLowerCase().trim();
this.setDataValue('title', val );
this.setDataValue('slug', val.split(" ").join("_"));
}
},
slug: { type: Sequelize.STRING, unique: true, allowNull: false },
creator: { type: Sequelize.INTEGER, references: { model: User, key: 'id' }}
},
{
timestamps: true,
updatedAt: false // I only want the field createdAt
}
)
mydb.authenticate().then(function(done){
if(mydb.sync({force: false}))
done()
}).catch(function(err, chat){
console.log(err);
});
module.exports = Chat;
//routes/admin.js
router.post("/dashboard",isAuthenticated, function(req,res){
if (req.body.chatName) {
try{
console.log(req.body.chatName);
console.log(Chat.create({ name: req.body.chatName, creator: req.user.id }));
}
catch (e){
console.log(e.message);
}
}
});
我只复制并粘贴了管理聊天室创建的功能,console.log(req.body.chatName);正确打印输入的名称