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

555
Views
Next.js con mongodb convertir a TypeScript

Instalé la aplicación next.js con la plantilla mongodb:

 npx create-next-app --e with-mongodb my-app

e instalé TypeScript también. Y necesito convertir /lib/mongodb.js a TypeScript

Actualmente se ve así, casi sin cambio de tipo

 // lib/mongodb.ts import { MongoClient } from 'mongodb' const uri = process.env.MONGODB_URI const options = {} let client let clientPromise: MongoClient if (!process.env.MONGODB_URI) { throw new Error('Please add your Mongo URI to .env.local') } if (process.env.NODE_ENV === 'development') { if (!global._mongoClientPromise) { client = new MongoClient(uri, options) global._mongoClientPromise = client.connect() } clientPromise = global._mongoClientPromise } else { client = new MongoClient(uri, options) clientPromise = client.connect() } export default clientPromise

Y está gritando: ingrese la descripción de la imagen aquí Por favor, ayúdame a definir los tipos adecuados, ¡soy bastante mecanografiado! ¡Gracias por adelantado!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Me encontré con el mismo problema ayer. ¡Afortunadamente, encontró una solución!

 import { MongoClient } from "mongodb"; if (!process.env.MONGODB_URI) { throw new Error("Please add your Mongo URI to .env.local"); } const uri: string = process.env.MONGODB_URI; let client: MongoClient; let clientPromise: Promise<MongoClient>; if (process.env.NODE_ENV === "development") { // In development mode, use a global variable so that the value // is preserved across module reloads caused by HMR (Hot Module Replacement). let globalWithMongoClientPromise = global as typeof globalThis & { _mongoClientPromise: Promise<MongoClient>; }; if (!globalWithMongoClientPromise._mongoClientPromise) { client = new MongoClient(uri); globalWithMongoClientPromise._mongoClientPromise = client.connect(); } clientPromise = globalWithMongoClientPromise._mongoClientPromise; } else { // In production mode, it's best to not use a global variable. client = new MongoClient(uri); clientPromise = client.connect(); } // Export a module-scoped MongoClient promise. By doing this in a // separate module, the client can be shared across functions. export default clientPromise;
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!