Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

2.4K
Views
typeORM No se encontraron cambios en el esquema de la base de datos; no se puede generar una migración. Para crear una nueva migración vacía, use el comando "typeormmigration:create"

Estoy haciendo un curso en el que usamos postgres express-node y reaccionamos (con mecanografiado) y typeORM. Todo ha funcionado bien hasta ahora, pero tengo un problema con typeORM y no sé qué está pasando y por qué ocurre este error.

El gran problema : Entonces, el problema es que estaba haciendo la autenticación, y en algún momento cambiamos el esquema de los usuarios en la base de datos, así que tuvimos que hacer una migración, pero, antes de la migración, hicimos npm run typeorm schema:drop , pero cuando probé, esto sucedió con la migración

Este es el primer comando que usé.

 npm run typeorm migration:generate -- --n create-users-table

este fue el error

 > new-typeorm-project@0.0.1 typeorm C:\Users\diego cifuentes\Desktop\Studying Backend\redit> ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table" bin.js migration:generate Generates a new migration file with sql needs to be executed to update schema. Opciones: -h, --help Muestra ayuda [booleano] -c, --connection Name of the connection on which run a query. [defecto: "default"] -n, --name Name of the migration class. [cadena de caracteres] [requerido] -d, --dir Directory where migration should be created. -p, --pretty Pretty-print generated SQL [booleano] [defecto: false] -f, --config Name of the file with connection configuration. [defecto: "ormconfig"] -o, --outputJs Generate a migration file on Javascript instead of Typescript [booleano] [defecto: false] --dr, --dryrun Prints out the contents of the migration instead of writing it to a file [booleano] [defecto: false] --ch, --check Verifies that the current database is up to date and that no migrations are needed. Otherwise exits with code 1. [booleano] [defecto: false] -v, --version Muestra número de versión [booleano] Falta argumento requerido: n npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! new-typeorm-project@0.0.1 typeorm: `ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the new-typeorm-project@0.0.1 typeorm script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\diego cifuentes\AppData\Roaming\npm-cache\_logs\2021-05-11T15_29_02_081Z-debug.log

Después de horas intentando buscar solución por todos lados, cambio el último comando por este

 npx typeorm migration:generate -- --n create-users-table

Y el error fue diferente esta vez, se ve así

 No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command

Entonces, dije, está bien, estoy más cerca de arreglar esto, pero... Después de horas (nuevamente) buscando una nueva respuesta, no pude encontrar nada, así que estoy llegando a un punto en el que necesito escribir esta publicación para solucionar mi problema. Así que ahora, déjame mostrarte mi ormconfig, mi paquete.json y la entidad que quiero migrar en mi base de datos postgres.

package.json (el script typeorm está al final)

 { "name": "new-typeorm-project", "version": "0.0.1", "description": "Awesome project developed with TypeORM.", "devDependencies": { "@types/bcrypt": "^5.0.0", "@types/cookie": "^0.4.0", "@types/cookie-parser": "^1.4.2", "@types/express": "^4.17.11", "@types/jsonwebtoken": "^8.5.1", "@types/morgan": "^1.9.2", "@types/node": "^15.0.2", "morgan": "^1.10.0", "nodemon": "^2.0.7", "ts-node": "^9.1.1", "typescript": "^4.2.4" }, "dependencies": { "bcrypt": "^5.0.1", "class-transformer": "^0.4.0", "class-validator": "^0.13.1", "cookie": "^0.4.1", "cookie-parser": "^1.4.5", "dotenv": "^9.0.1", "express": "^4.17.1", "jsonwebtoken": "^8.5.1", "pg": "^8.4.0", "reflect-metadata": "^0.1.10", "typeorm": "0.2.32" }, "scripts": { "start": "ts-node src/server.ts", "dev": "nodemon --exec ts-node src/server.ts", "typeorm": "ts-node ./node_modules/typeorm/cli.js" } }

ormconfing.json Nota rápida : cambié entidades, migraciones y suscriptores a .js, porque con .ts siempre me daba error.

 { "type": "postgres", "host": "localhost", "port": 5432, "username": "**", "password": "**", "database": "**", "synchronize": true, "logging": true, "entities": ["src/entities/**/*.js"], "migrations": ["src/migrations/**/*.js"], "subscribers": ["src/subscribers/**/*.js"], "cli": { "entitiesDir": "src/entities", "migrationsDir": "src/migrations", "subscribersDir": "src/subscribers" } }

Y lo último que quiero mostrarles, aunque no sea tan importante, este es el esquema de usuarios.

 import { Entity as TOEntity, Column, Index, BeforeInsert, OneToMany } from "typeorm"; import bcrypt from "bcrypt"; import { IsEmail, Length } from "class-validator"; import { Exclude } from "class-transformer"; import Entity from "./Entity"; // import Post from "./Post"; @TOEntity("users") export default class User extends Entity { constructor(user: Partial<User>) { super(); Object.assign(this, user); } @Index() @IsEmail() @Column({ unique: true }) email: string; @Index() @Length(3, 200) @Column({ unique: true }) username: string; @Exclude() @Length(6, 200) @Column() password: string; // @OneToMany(() => Post, post => post.user) // posts: Post[]; @BeforeInsert() async hashedPassword() { this.password = await bcrypt.hash(this.password, 6); } }

Objetivo final : Entonces, si puedes ayudarme con esto, me salvarás la vida. Una última cosa es que traté de publicar mis problemas primero en el sitio web español de desbordamiento de pila, pero nadie pudo ayudarme, así que tal vez aquí alguien lo haga, ¡gracias por su tiempo y cuídese!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para mí, el ormconfig.json fue así,

 "entities": [ "dist/entity/**/*.ts" ], "migrations": [ "src/migration/**/*.ts" ], "subscribers": [ "src/subscriber/**/*.ts" ],

cambiándolo a

 "entities": [ "src/entity/**/*{.js,.ts}" ], "migrations": [ "src/migration/**/*{.js,.ts}" ], "subscribers": [ "src/subscriber/**/*{.js,.ts}" ],

generó la migración correctamente.

Y el script package.json es como este "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"

Y el comando usado es

npm ejecutar typeorm migración: generar -- -n FileAddTemporaryDeletedFields -p --dr --ch

over 4 years ago · Santiago Trujillo Report

0

Cambie sus entities , migrations y subscribers a su directorio dist .

p.ej:

 entities: ["dist/entities/**/*{.js,.ts}"], migrations: ["dist/migrations/**/*{.js,.ts}"], subscribers: ["dist/subscribers/**/*{.js,.ts}"],

dist directorio es el directorio que se crea cuando construyes la aplicación. Puede encontrar su directorio dist usando tsconfig.json -> compilerOptions -> outDir .

Luego, vuelva a compilar su aplicación con npm run build e intente generar las migraciones.

over 4 years ago · Santiago Trujillo Report

0

He visto este error, y si no me equivoco es porque estaba intentando crear un banco que ya estaba creado.

Este comando a continuación elimina todas las tablas:

yarn typeorm query "DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT USAGE ON SCHEMA public to PUBLIC; GRANT CREATE ON SCHEMA public to PUBLIC; COMMENT ON SCHEMA public IS 'standard public schema';"

luego:

yarn typeorm --migration:generate -n migration_name -d path/to/your/migrations/

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!