【问题标题】:How to seed uuidv4 with sequelize如何使用 sequelize 播种 uuidv4
【发布时间】:2018-03-05 10:18:56
【问题描述】:

我正在尝试使用 sequilize generateUUID 播种 uuid 但我收到此错误Seed file failed with error: sequelize.Utils.generateUUID is not a function TypeError: sequelize.Utils.generateUUID is not a function

如何播种 UUID?

    return queryInterface.bulkInsert('companies', [{
        id: sequelize.Utils.generateUUID(),
        name: 'Testing',
        updated_at: new Date(),
        created_at: new Date()
    }]);

【问题讨论】:

    标签: node.js sequelize.js sequelize-cli


    【解决方案1】:

    只需安装 uuid:

    npm install uuid
    

    在你的种子文件上:

    const uuidv4 = require('uuid/v4');
    
    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.bulkInsert('yourTableName', [
          {
            id: uuidv4()
          }],
     {});
    

    【讨论】:

    • Sequelize 在底层使用了uuid,所以这个包应该已经可用了。不过,Sequelize 并没有以有用的方式公开 uuidv4 方法。
    • 现在得到DeprecationWarning: Deep requiring like 'const uuidv4 = require('uuid/v4');' is deprecated as of uuid@7.x. Please require the top-level module when using the Node.js CommonJS module or use ECMAScript Modules when bundling for the browser. See https://github.com/uuidjs/uuid#deep-requires-now-deprecated for more information. 当我切换到推荐的导入语法时,我得到一个不同的错误。
    【解决方案2】:

    由于它包含在 DataTypes 包中,因此按照 Matt 的建议使用 already available 是有意义的。你可以这样使用它:

    {
        ...,
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        ...
    }
    

    【讨论】:

    • 哇!将键从“default”更改为“defaultValue”为我解决了这个问题。谢谢
    • 很好,与上面的答案相比,这已经很好了,因为 sequelize 需要它来实现。
    【解决方案3】:

    npm install uuid

    将其导入您的播种文件

    const { v4: uuidv4 } = require('uuid');
    
    return queryInterface.bulkInsert('companies', [{
        id: uuidv4(),
        name: 'Testing',
        updated_at: new Date(),
        created_at: new Date()
    }]);
    

    See more on the uuid documentation

    【讨论】:

    • 我想,链接是 Sequelize 文档
    • 不...这是 uuid 文档...我已经更新了答案以澄清这一点..感谢您指出。
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2018-04-13
    • 2022-12-11
    • 2017-08-26
    • 2023-02-21
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多