【问题标题】:Sequelize - Custom Create MethodSequelize - 自定义创建方法
【发布时间】:2017-02-13 03:58:54
【问题描述】:

是否可以在Sequelize 中创建自定义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 参数而不是thumbnailPhotoURL 参数调用User.create

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    可以在创建前使用钩子,无需定义自定义创建函数

    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();
    });
    

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 2016-08-07
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2018-02-04
      相关资源
      最近更新 更多