Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda