Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
initialize mongodb in next js startup

hi every body i have question on connecting nextJs to mongodb on startup of server. as u know nextjs is fs framework and im migrationg from node/express to it but my problem is how to connect server to database at startup of server as i did in express? there is now where to put my initalizing code in nextjs?am i saying correct? i saw some code to to that but there were typescript codes that im not familiar with them

on the other hand i'm able to do that on serverside functions like getStaticProps or getServerSideProps this is my code dbinit.js

import mongoose from "mongoose";
export const dbStatus = () => mongoose.connection.readyState;
export default function dbConnect() {
  if (dbStatus == 1) return "database is connected";
  mongoose.connect(
    `mongodb://localhost:${process.env.DBPORT}/${process.env.DBNAME}`
  );
}

index.js

export async function getServerSideProps() {
  const result = await dbConnect();
  console.log(dbStatus());
  return {
    props: {},
  };
}

with this code im able to connect to mongodb but there are some problems and the most important is that mycode isnot cleancode

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

In NextJS, we can connect MongoDB as middleware. This is very similar to the Express middleware approach as shown below.

// middleware/database.js

import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';

const client = new MongoClient('{YOUR-MONGODB-CONNECTION-STRING}', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function database(req, res, next) {
  if (!client.isConnected()) await client.connect();
  req.dbClient = client;
  req.db = client.db('MCT');
  return next();
}

const middleware = nextConnect();

middleware.use(database);

export default middleware;

For more details, you can refer to this official how-to doc for step-by-step guidance. Here is the example repository used.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda