2015-12-21 98 views
3

我在续集中有以下模型。创建关联sequalize的记录

var User = sequelize.define('User', { 

_id: { 
    type: DataTypes.INTEGER, 
    allowNull: false, 
    primaryKey: true, 
    autoIncrement: true 
}, 
name: DataTypes.STRING, 
email: { 
    type: DataTypes.STRING, 
    unique: { 
    msg: 'The specified email address is already in use.' 
    }, 
    validate: { 
    isEmail: true 
    } 
}, 
role: { 
    type: DataTypes.STRING, 
    defaultValue: 'user' 
} 
} 

该模型具有一些asssoications /关系如下:

User.belongsToMany(models.Skill, {through: 'UserSkill', as: 'Skills'}); 

节省I使用下面的请求有效负载的新的记录:

{ 
"name": "Test User", 
"email": "[email protected]",, 
"skills" : [2,3] 
} 

其中技能应该表示的阵列我们已经在数据库中拥有技能,如何保存新记录并同时验证所有技能?

回答

0

这是一种方式,可能是它可以帮助你:)

router.post('/assignSkills', function (req, res, next) { 
var record = req.body.data; 
model.users.findOne({ 
    where: { id: record.userId } 
}).then(function (user) { 
    model.skills.findOne({ 
     where: { id: record.skillId } 
    }).then(function (skill) { 
     user.addSkill(skill); 
     res.send(user); 
    }); 
}); 
}); 
相关问题