【问题标题】:How to use BLOB data type with sequalize migrations如何在 sequelize 迁移中使用 BLOB 数据类型
【发布时间】:2020-06-29 12:57:04
【问题描述】:

我最近开始使用nodejs和sequalize,我一直在开发一个示例应用程序。在我的应用程序中,我有用户。在 sequalize 中使用播种机添加一些虚拟数据时,我遇到了如何使用播种机添加 BLOB 类型的个人资料图片的问题。

我的示例模型和种子文件如下所示。

module.exports = (sequelize, DataTypes) => {
  const user = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    fullName: DataTypes.STRING,
    profilePicture: DataTypes.BLOB
  }, {});
  user.associate = function(models) {
    // associations can be defined here
  };
  return user;
};

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkInsert('People', [{
        name: 'John Doe',
        isBetaMember: false
      }], {});
    */
    return queryInterface.bulkInsert('users', [
      {
        firstName: 'Andrew',
        lastName: 'Perera',
        fullName: 'Andrew Perera',
        createdAt: new Date(),
        updatedAt: new Date(),
        profilePicture: <WHAT IS THIS>
      }
      ]);
  },

  down: (queryInterface, Sequelize) => {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.bulkDelete('People', null, {});
    */
    return queryInterface.bulkDelete('users', null, {});
  }
};

我应该怎么做?

【问题讨论】:

    标签: mysql node.js express orm sequelize.js


    【解决方案1】:

    您可以为其分配一个buffer 值。下面的示例使用"sequelize": "^5.21.3"

    对于现实世界的情况,您可以像这样创建缓冲区:

    import fs from 'fs';
    const filepath = path.resolve(__dirname, './image.jpeg');
    const profilePicture = Buffer.from(fs.readFileSync(filepath));
    

    然后,将此 BLOB 数据写入图像文件:

    import fs from 'fs';
    const outputFilepath = path.resolve(__dirname, './output.jpeg');
    fs.writeFileSync(outputFilepath, user.profilePicture, 'base64');
    
    import { sequelize } from '../../db';
    import { Model, DataTypes } from 'sequelize';
    
    class User extends Model {}
    User.init(
      {
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        fullName: DataTypes.STRING,
        profilePicture: DataTypes.BLOB,
      },
      { sequelize, modelName: 'users', timestamps: true },
    );
    
    (async function test() {
      try {
        await sequelize.sync({ force: true });
        // seed
        await User.bulkCreate([
          {
            firstName: 'Andrew',
            lastName: 'Perera',
            fullName: 'Andrew Perera',
            createdAt: new Date(),
            updatedAt: new Date(),
            profilePicture: Buffer.from('whatever'),
          },
        ]);
        const user = await User.findOne();
        console.log('user:', user);
      } catch (error) {
        console.log(error);
      } finally {
        await sequelize.close();
      }
    })();
    

    执行结果:

    Executing (default): INSERT INTO "users" ("id","firstName","lastName","fullName","profilePicture","createdAt","updatedAt") VALUES (DEFAULT,'Andrew','Perera','Andrew Perera',E'\\x7768617465766572','2020-03-19 04:14:20.981 +00:00','2020-03-19 04:14:20.981 +00:00') RETURNING *;
    Executing (default): SELECT "id", "firstName", "lastName", "fullName", "profilePicture", "createdAt", "updatedAt" FROM "users" AS "users" LIMIT 1;
    user: { id: 1,
      firstName: 'Andrew',
      lastName: 'Perera',
      fullName: 'Andrew Perera',
      profilePicture: <Buffer 77 68 61 74 65 76 65 72>,
      createdAt: 2020-03-19T04:14:20.981Z,
      updatedAt: 2020-03-19T04:14:20.981Z 
    

    数据库中的虚拟数据记录:

    =# select * from users;
     id | firstName | lastName |   fullName    | profilePicture |         createdAt          |         updatedAt
    ----+-----------+----------+---------------+----------------+----------------------------+----------------------------
      1 | Andrew    | Perera   | Andrew Perera | \x706963       | 2020-03-19 04:11:55.868+00 | 2020-03-19 04:11:55.868+00
    (1 row)
    

    【讨论】:

    • 根据上面使用BLOB数据类型。我做到了。运行种子文件时的。我收到此错误。错误:第 1 行的“profilePicture”列的数据太长。然后我将数据类型更改为 LONG_BLOB。然后我得到了这个错误。错误:无法读取未定义的属性“toString”。这里有什么问题
    • @YasiruNilan 播种虚拟数据Buffer.from('whatever')是否会发生此错误?
    • 当时出现了初始错误。然后我将数据类型更改为 LONG_BLOB 然后问题出现在运行迁移时
    猜你喜欢
    • 2015-09-11
    • 2020-02-14
    • 2019-05-31
    • 2020-10-21
    • 2015-03-06
    • 2020-02-01
    • 2018-09-14
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多