2015-12-21 96 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); 
    }); 
}); 
}); 
相關問題