Sequelize – 自定义创build方法

是否有可能在Sequelize创build一个自定义的create方法。 我希望它能传递一个URL来下载缩略图,然后用这些数据调用一个方法来下载照片,上传到S3,然后将S3 URL保存为thumbnailPhotoURL。

这是我正在尝试做的语法的一个例子:

 var Sequelize = require('sequelize'); var sequelize = new Sequelize('database', 'username', 'password'); var User = sequelize.define('user', { username: Sequelize.STRING, birthday: Sequelize.DATE, thumbnailPhotoURL: Sequelize.STRING }); sequelize.sync().then(function() { return User.create({ username: 'janedoe', birthday: new Date(1980, 6, 20), // this will be used to download and upload the thumbnailPhoto to S3 urlToDownloadThumbnailPhotoFrom: 'http://example.com/test.png' }); }).then(function(jane) { console.log(jane.get({ plain: true })); }); 

注意我是如何使用urlToDownloadThumbnailPhotoFrom参数调用User.create ,而不是使用thumbnailPhotoURL参数

你可以在创build钩子之前使用,不需要定义一个自定义的创build函数

 var Sequelize = require('sequelize'); var sequelize = new Sequelize('database', 'username', 'password'); var User = sequelize.define('user', { username: Sequelize.STRING, birthday: Sequelize.DATE, thumbnailPhotoURL: Sequelize.STRING }); User.beforeCreate(function(model, options, cb) { var urlToDownloadThumbnailPhotoFrom = model.urlToDownloadThumbnailPhotoFrom; //.....Here you write the logic to get s3 url using urlToDownloadThumbnailPhotoFrom and then assign it to model and call the call back it will automatically get saved model.thumbnailPhotoURL = thumbnailPhotoURL; cb(); });