How to seed uuidv4 with sequelize
Asked Answered
A

3

14

I am trying to seed a uuid using sequilize generateUUID but i get this error Seed file failed with error: sequelize.Utils.generateUUID is not a function TypeError: sequelize.Utils.generateUUID is not a function

how do i seed a UUID?

    return queryInterface.bulkInsert('companies', [{
        id: sequelize.Utils.generateUUID(),
        name: 'Testing',
        updated_at: new Date(),
        created_at: new Date()
    }]);
Alane answered 24/9, 2017 at 9:0 Comment(0)
G
13

just install uuid:

npm install uuid

and on your seed file:

const uuidv4 = require('uuid/v4');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('yourTableName', [
      {
        id: uuidv4()
      }],
 {});
Garbo answered 25/9, 2017 at 6:57 Comment(2)
Sequelize does use uuid under the hood so the package should already be available. Sequelize doesn't expose the uuidv4 method in a useful way though.Approval
Now getting DeprecationWarning: Deep requiring like 'const uuidv4 = require('uuid/v4');' is deprecated as of [email protected]. 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. And when I switch to the recommended import syntax I get a different error.Meroblastic
T
7

Since it's included in the DataTypes package, would make sense to use what is already available as Matt suggested. You can use it in this way:

{
    ...,
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    ...
}
Tocsin answered 12/12, 2020 at 22:36 Comment(2)
Wow! Changing the key from "default" to "defaultValue" solved it for me. ThanksBoisterous
Nice, This is far good in comparison to the above answers as sequelize have it all required for this to achieve.Aeolis
C
6

npm install uuid

import it on your seeder file

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

Commonwealth answered 28/3, 2021 at 12:11 Comment(2)
I thought, the link is to Sequelize documentationKumkumagai
Nah... it's uuid documentation... I have updated the answer to clarify that.. thanks for pointing it out.Commonwealth

© 2022 - 2024 — McMap. All rights reserved.