No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Modificando una entidad

15/27
Recursos

Aportes 17

Preguntas 18

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

Para generar el archivo add-role.js hay que correr el comando

npm run migrations:generate add-role

Con sequelize.sync() no se puede alterar una tabla que ya est谩 creada ya que 煤nicamente lee el modelo, y en caso de hacer alguna modificaci贸n, se queda con la primera versi贸n (no se puede agregar un atributo m谩s). Con las migraciones es m谩s flexible ya que s铆 se pueden hacer modificaciones y tener todo de una forma organizada.

Para agregar una columna se hace con el m茅todo addColumn, se define el nombre de la tabla, seguido del nombre de la columna, finalmente el esquema (nulo, string, etc), en ese caso se define el esquema del campo en espec铆fico.

await queryInterface.addColumn(USER_TABLE, 'role', UserSchema.

Para quitar la columna se usa el m茅todo removeColumn definiendo el nombre de la tabla y de la columna.

await queryInterface.removeColumn(USER_TABLE, 'role');

Se debe correr la migraci贸n para ejecutar los cambios, esta va a correr a partir de la 煤ltima migraci贸n.

脡xito rotundo

馃捑 DB Generation

鈩癸笍 Repositorio: Link
.

user.js. Definici贸n de esquema

import { DataTypes, Sequelize as SequelizeClient } from 'sequelize';

/**
 * @description description of each field in the table
 * @typedef {Object} field definition
 * @property {boolean} allowNull - false=NOT NULL
 * @property {boolean} autoIncrement - each insert, increase the counter
 * @property {boolean} primaryKey - define is primary key
 * @property {boolean} type - expresion to match SQL type
 * @property {boolean} unique - difne as unique the field
 * @property {boolean} field - rename the field
 */
export default {
    id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER,
    },
    email: {
        allowNull: false,
        type: DataTypes.STRING,
        unique: true,
    },
    password: {
        allowNull: false,
        type: DataTypes.STRING,
    },
    createdAt: {
        allowNull: false,
        type: DataTypes.DATE,
        field: 'created_at',
        defaultValue: SequelizeClient.NOW,
    },
    updatedAt: {
        allowNull: false,
        type: DataTypes.DATE,
        field: 'updated_at',
        defaultValue: SequelizeClient.NOW,
    },
};

.

config.js. Configuraci贸n de entornos

import Sequelize from './../libs/sequelize';

module.exports = Sequelize.migration;

.

鈾伙笍 .sequelizerc Configuraci贸n del sequelize

require('@babel/register');

module.exports = {
    config: './src/mocks/config.js',
    'migrations-path': './src/mocks/migrations',
    'seeders-path': './src/mocks/seeders',
};

鈾伙笍 package.json. Adici贸n de scrips de generaci贸n y ejecuci贸n

        "seeds:generate": "sequelize-cli seed:generate --name",
        "seeds:run": "sequelize-cli db:seed:all",
        "migrations:generate": "sequelize-cli migration:generate --name",
        "migrations:run": "sequelize-cli db:migrate",
        "db:generate": "npm run migrations:run && npm run seeds:run",

.

Generaci贸n de scripts para migration y seeds

create-user-table.js

import userSchema from '../models/user';

module.exports = {
    up: async (queryInterface) => {
        await queryInterface.createTable('users', userSchema);
    },

    down: async (queryInterface) => {
        await queryInterface.drop('users');
    },
};

users.js

.
馃挕Para la generaci贸n de Seeds, puede ocupar un generador de mocks como Mockaroo

module.exports = {
    up: (queryInterface) => {
        return queryInterface.bulkInsert('users', [
            {
                email: '[email protected]',
                password: 'dIkttoW58AZl',
                created_at: new Date(),
                updated_at: new Date(),
            },
            {
                email: '[email protected]',
                password: 'LWGHo4Sf',
                created_at: new Date(),
                updated_at: new Date(),
            },
            {
                email: '[email protected]',
                password: '8iKZ14bBA',
                created_at: new Date(),
                updated_at: new Date(),
            },
            {
                email: '[email protected]',
                password: 'GLY4O1',
                created_at: new Date(),
                updated_at: new Date(),
            },
            {
                email: '[email protected]',
                password: 'dWYttZ4',
                created_at: new Date(),
                updated_at: new Date(),
            },
        ]);
    },
    down: (queryInterface) => {
        return queryInterface.bulkDelete('users', null, {});
    },
};

Hay un salto de edici贸n, no se ve el proceso para crear la nueva migraci贸n add-role para crearlo tenemos que hacer uso de nuestro script :

npm run migrations:generate add-role

Una cosa importante es que cuando corremos una migraci贸n, queda un registro de esa migraci贸n en base de datos de dicha migraci贸n. Por ejemplo, recientemente corrimos el comando de creaci贸n de la tabla users, entonces en la base de datos se crear谩 una carpeta llamada SequelizeMeta, en donde quedar谩 un registro de que se corri贸 dicha migraci贸n.
Por lo que si corremos ahora esta 煤ltima migraci贸n de agregar una columna, Sequelize consultar谩 en base de datos en el registro de migraciones cual fue la 煤ltima migraci贸n que hizo en dicha carpeta, por lo que no volver谩 a correr una migraci贸n que ya quedo registrada, sino de todas de las que no tiene registro en base de datos. Es decir, una vez que corremos una migraci贸n, debemos crear otra migraci贸n si queremos realizar alguna otra operaci贸n, exceptuando que no sea ir para atr谩s de la 煤ltima migraci贸n que hicimos

Muy bien ya me quedo

Excelente clase muy buena info.

ahora si todo bien funciono aunque tuve que corregir algunos temas pero funcion鈥 馃槃

[
  {
    "id": 1,
    "email": "[email protected]",
    "password": "12345678",
    "role": "customer",
    "createdAt": "2021-11-25T11:03:34.941Z"
  },
  {
    "id": 2,
    "email": "[email protected]",
    "password": "12345678",
    "role": "customer",
    "createdAt": "2021-11-25T11:03:48.567Z"
  }
]
tengo un problema, despues de crear la migracion y crear el role y querer consultar con insomnia, se queda pensando y me suielta que no existe el campo upodateAt, cosa que no debe tener sentido porque nunca creamos un campo asi, pero por lo que veo es por defecto que la bd lo hace, consultando me dice que tengo que crear ese campo y lo creo y aun asi persiste el problema, quedo atento pongo aqui el error que sale antes de la creacion del campo y despues ```js _original: { email: '[email protected]', password: '123456798', role: 'customer' }, details: [ { message: '"role" is not allowed', path: [Array], type: 'object.unknown', context: [Object] } ], isBoom: true, isServer: false, data: null, output: { statusCode: 400, payload: { statusCode: 400, error: 'Bad Request', message: '"role" is not allowed' }, headers: {} } } Error at Query.run (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/dialects/postgres/query.js:50:25) at /home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/sequelize.js:315:28 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async PostgresQueryInterface.select (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/dialects/abstract/query-interface.js:407:12) at async User.findAll (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/model.js:1140:21) at async UserService.find (/home/sgutierrez/Documents/Proyectos/curso_node_express/api/services/user.service.js:18:17) at async /home/sgutierrez/Documents/Proyectos/curso_node_express/api/routes/users.router.js:16:19 { name: 'SequelizeDatabaseError', parent: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:39:38) at Socket.<anonymous> (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream_base_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, original: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:39:38) at Socket.<anonymous> (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream_base_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, sql: 'SELECT "id", "email", "password", "role", "create_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: {} } [Error [ValidationError]: "role" is not allowed] { _original: { email: '[email protected]', password: '123456798', role: 'customer' }, details: [ { message: '"role" is not allowed', path: [Array], type: 'object.unknown', context: [Object] } ], isBoom: true, isServer: false, data: null, output: { statusCode: 400, payload: { statusCode: 400, error: 'Bad Request', message: '"role" is not allowed' }, headers: {} } } Error at Query.run (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/dialects/postgres/query.js:50:25) at /home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/sequelize.js:315:28 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async PostgresQueryInterface.select (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/dialects/abstract/query-interface.js:407:12) at async User.findAll (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/sequelize/lib/model.js:1140:21) at async UserService.find (/home/sgutierrez/Documents/Proyectos/curso_node_express/api/services/user.service.js:18:17) at async /home/sgutierrez/Documents/Proyectos/curso_node_express/api/routes/users.router.js:16:19 { name: 'SequelizeDatabaseError', parent: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:39:38) at Socket.<anonymous> (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream_base_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, original: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/parser.js:39:38) at Socket.<anonymous> (/home/sgutierrez/Documents/Proyectos/curso_node_express/node_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream_base_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, sql: 'SELECT "id", "email", "password", "role", "create_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: {} } ^C ``` \_original: { email: '[email protected]', password: '123456798', role: 'customer' }, details: \[ { message: '"role" is not allowed', path: \[Array], type: 'object.unknown', context: \[Object] } ], isBoom: true, isServer: false, data: null, output: { statusCode: 400, payload: { statusCode: 400, error: 'Bad Request', message: '"role" is not allowed' }, headers: {} } } Error at Query.run (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/dialects/postgres/query.js:50:25) at /home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/sequelize.js:315:28 at process.processTicksAndRejections (node:internal/process/task\_queues:95:5) at async PostgresQueryInterface.select (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/dialects/abstract/query-interface.js:407:12) at async User.findAll (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/model.js:1140:21) at async UserService.find (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/api/services/user.service.js:18:17) at async /home/sgutierrez/Documents/Proyectos/curso\_node\_express/api/routes/users.router.js:16:19 { name: 'SequelizeDatabaseError', parent: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:39:38) at Socket.\<anonymous> (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream\_base\_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse\_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create\_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, original: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:39:38) at Socket.\<anonymous> (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream\_base\_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse\_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create\_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, sql: 'SELECT "id", "email", "password", "role", "create\_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: {} } \[Error \[ValidationError]: "role" is not allowed] { \_original: { email: '[email protected]', password: '123456798', role: 'customer' }, details: \[ { message: '"role" is not allowed', path: \[Array], type: 'object.unknown', context: \[Object] } ], isBoom: true, isServer: false, data: null, output: { statusCode: 400, payload: { statusCode: 400, error: 'Bad Request', message: '"role" is not allowed' }, headers: {} } } Error at Query.run (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/dialects/postgres/query.js:50:25) at /home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/sequelize.js:315:28 at process.processTicksAndRejections (node:internal/process/task\_queues:95:5) at async PostgresQueryInterface.select (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/dialects/abstract/query-interface.js:407:12) at async User.findAll (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/sequelize/lib/model.js:1140:21) at async UserService.find (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/api/services/user.service.js:18:17) at async /home/sgutierrez/Documents/Proyectos/curso\_node\_express/api/routes/users.router.js:16:19 { name: 'SequelizeDatabaseError', parent: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:39:38) at Socket.\<anonymous> (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream\_base\_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse\_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create\_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, original: error: column "updatedAt" does not exist at Parser.parseErrorMessage (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:287:98) at Parser.handlePacket (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:126:29) at Parser.parse (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/parser.js:39:38) at Socket.\<anonymous> (/home/sgutierrez/Documents/Proyectos/curso\_node\_express/node\_modules/pg-protocol/dist/index.js:11:42) at Socket.emit (node:events:514:28) at addChunk (node:internal/streams/readable:324:12) at readableAddChunk (node:internal/streams/readable:297:9) at Readable.push (node:internal/streams/readable:234:10) at TCP.onStreamRead (node:internal/stream\_base\_commons:190:23) { length: 109, severity: 'ERROR', code: '42703', detail: undefined, hint: undefined, position: '71', internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'parse\_relation.c', line: '3713', routine: 'errorMissingColumn', sql: 'SELECT "id", "email", "password", "role", "create\_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: undefined }, sql: 'SELECT "id", "email", "password", "role", "create\_at" AS "createdAt", "updatedAt" FROM "users" AS "User";', parameters: {} } ^C
Creo que una buena practica en migraciones cuando vamos hacer alguna modificaci贸n debemos ser claros que har谩 y donde lo har谩 por ejemplo: Hicimos esto en el curso: `npm rum migrations:generate add-role` Deberiamos especificar a que tabla por ejemplo `npm rum migrations:generate add-role-to-users` Corr铆janme si me equivoco
Una buena pr谩ctica en el uso de migraciones es que cada migraci贸n realice estrictamente el cambio necesario sin alterar nuestros esquemas. De esta manera, podemos asegurar un correcto funcionamiento de nuestros "rollback" y mantener un registro de c贸mo ha evolucionado nuestra base de datos. para este parte yo cree una migraci贸n llamada: `-add-column-role-to-user-table` la cual contiene el cambio de agregar la columna rol en mi tabla use, haciendo uso de `sequelize.transaction` ![](https://static.platzi.com/media/user_upload/image-c8215fe9-841d-4aa4-829c-dd3eade05d75.jpg) Si encuentran una mejor forma me comparten en las respuestas. :D
Bueno al fin pode solucionar el tema de el updatedAt el problema era que cuando creaba la migracion de create user y crear el role, al querer consultar la informacion o crear nuevos users, me tiraba un error de que el campo updatedAt no existia, pero antes de la migracion postgres lo creaba por defecto, pero al hacer la migracion no pasaba ese campo, mi solucion fue la siguiente. 1\. al crear el create-user agregue ese campo debajo del createdAt, igual solo que cambia nombres 1. iniciaba la migracion y luego creo el campo role y listo ya funcionaba. Bueno esa fue mi solucion, puede que alguien con mas experienciapueda tener una mejor
Alguien sabe como solucionar este error? \> [email protected] migrations:run \> sequelize-cli db:migrate Sequelize CLI \[Node: 20.9.0, CLI: 6.6.2, ORM: 6.35.2] Loaded configuration file "db\config.js". Using environment "development". \== 20231228214633-create-user: migrating ======= ERROR: No Sequelize instance passedconst { Sequelize } = require('sequelize')const { config } = require('../config/config')const setupModels = require('../db/models') const USER = encodeURIComponent(config.dbUser)const PASSWORD = encodeURIComponent(config.dbPassword) const sequelize = new Sequelize(聽 聽 config.dbName, 聽 聽 USER,聽 聽 PASSWORD, {聽 聽 host: config.dbHost,聽 聽 port: config.dbPort,聽 聽 dialect: 'mysql',聽 聽 logging: true,聽 聽 define: {聽 聽 聽 聽 freezeTableName: true聽 聽 }}) setupModels(sequelize) module.exports = sequelize config.js:require('dotenv').config() const config = {聽 聽 env: process.env.NODE\_ENV || 'dev',聽 聽 port: process.env.PORT || 3000,聽 聽 dbUser: process.env.DB\_USER,聽 聽 dbPassword: process.env.DB\_PASSWORD,聽 聽 dbHost: process.env.DB\_HOST,聽 聽 dbName: process.env.DB\_NAME,聽 聽 dbPort: process.env.DB\_PORT,} const URI = `mysql://${config.dbUser}:${encodeURIComponent(config.dbPassword)}@${config.dbHost}:${config.dbPort}/${config.dbName}`; module.exports = { config, URI} ```js require('dotenv').config() const config = { env: process.env.NODE_ENV || 'dev', port: process.env.PORT || 3000, dbUser: process.env.DB_USER, dbPassword: process.env.DB_PASSWORD, dbHost: process.env.DB_HOST, dbName: process.env.DB_NAME, dbPort: process.env.DB_PORT, } const URI = `mysql://${config.dbUser}:${encodeURIComponent(config.dbPassword)}@${config.dbHost}:${config.dbPort}/${config.dbName}`; module.exports = { config, URI} ```sequelize.js: const { URI } = require('../config/config') module.exports = {聽 聽 development: {聽 聽 聽 聽 url: URI,聽 聽 聽 聽 dialect: 'mysql',聽 聽 },聽 聽 production: {聽 聽 聽 聽 url: URI,聽 聽 聽 聽 dialect: 'mysql',聽 聽 },}; ```js const { Sequelize } = require('sequelize') const { config } = require('../config/config') const setupModels = require('../db/models') const USER = encodeURIComponent(config.dbUser) const PASSWORD = encodeURIComponent(config.dbPassword) const sequelize = new Sequelize( config.dbName, USER, PASSWORD, { host: config.dbHost, port: config.dbPort, dialect: 'mysql', logging: true, define: { freezeTableName: true } }) setupModels(sequelize) module.exports = sequelize ```/db/config.js ```js const { URI } = require('../config/config') module.exports = { development: { url: URI, dialect: 'mysql', }, production: { url: URI, dialect: 'mysql', }, }; ```

Si definen los modelos de esta manera 馃憞馃徑

const { DataTypes, Sequelize } = require("sequelize");
const { sequelize } = require("../db");

const User = sequelize.define("user", {
  id: {
    allowNull: false,

    primaryKey: true,
    type: DataTypes.STRING,
  },
  email: {
    allowNull: false,
    type: DataTypes.STRING,
    unique: true,
  },
  password: {
    allowNull: false,
    type: DataTypes.STRING,
  },
  role: {
    allowNull: false,
    type: DataTypes.STRING,
    defaultValue: "customer",
  },
  createdAt: {
    allowNull: false,
    type: DataTypes.DATE,
    field: "create_at",
    defaultValue: Sequelize.NOW,
  },
});

module.exports = User;

Entonces deben escribir la migracion de esta manera 馃憞馃徑

"use strict";

const User = require("../models/user.model");

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  up: async (queryInterface) => {
    await queryInterface.createTable(User.getTableName(), User.getAttributes());
  },

  down: async (queryInterface) => {
    await queryInterface.dropTable(User.getTableName());
  },
};

npm run migrations:generate add-role

excelente curso, hecho en peque帽as capsulas para ir directamente al video, justo necesitaba este video para aplicarlo en mis proyectos