No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

No se trata de lo que quieres comprar, sino de quién quieres ser. Aprovecha el precio especial.

Antes: $249

Currency
$209

Paga en 4 cuotas sin intereses

Paga en 4 cuotas sin intereses
Suscríbete

Termina en:

15 Días
17 Hrs
36 Min
40 Seg

Modificando una entidad

15/27
Recursos

Aportes 18

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

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

💾 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, {});
    },
};

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

Tuve el siguiente problema: `Sequelize CLI [Node: 20.12.2, CLI: 6.6.2, ORM: 6.37.3]` `Loaded configuration file "api\db\config.js".` `Using environment "development".` `== 20240719181909-add-role: migrating =======` `ERROR: Cannot read properties of undefined (reading 'toString')` para solucionarlo tuve que modificar una parte del codigo: ```js 'use strict'; /** @type {import('sequelize-cli').Migration} */ const { UserSchema, USER_TABLE } = require('../models/user.model'); module.exports = { async up (queryInterface) { await queryInterface.addColumn(USER_TABLE, 'role', { type: UserSchema.role.type, allowNull: UserSchema.role.allowNull, defaultValue: UserSchema.role.defaultValue, }); }, async down (queryInterface) { await queryInterface.removeColumn(USER_TABLE, 'role', UserSchema); } }; ```'use strict'; */\*\* @type {import('sequelize-cli').Migration} \*/*const { UserSchema, USER\_TABLE } = require('../models/user.model');module.exports = {    async up (*queryInterface*) {        await *queryInterface*.addColumn(USER\_TABLE, 'role', {            type: UserSchema.role.type,            allowNull: UserSchema.role.allowNull,            defaultValue: UserSchema.role.defaultValue,        });    },     async down (*queryInterface*) {        await *queryInterface*.removeColumn(USER\_TABLE, 'role', UserSchema);    }};

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