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

545
Visualizações
"MongoError: Topology is closed, please connect" in MongoDB & NodeJS program

I'm using MongoDB Atlas and Node.js. I'm trying to insert a document to the collection "B99", but i get the error: MongoError: Topology is closed, please connect.

This is what I've tried so far (from answers in other posts, but none of them have worked):

  1. Changing my password for the user to only letters (no numbers or symbols)
  2. Removing client.close(); at the end.
  3. Reformatting my code as shown below (got the "format" from another post).
  4. Adding my IP to the whitelist on the Network Access page on MongoDB Atlas.
var MongoClient = require('mongodb').MongoClient;
const MongoUsername = process.env.MONGO_USERNAME
const MongoPassword = process.env.MONGO_PASSWORD
var uri = "mongodb+srv://" + MongoUsername + ":" + MongoPassword + "@testcluster.8mz1j.mongodb.net/BrooklynNineNine?retryWrites=true&w=majority";

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
  const collection = client.db("BrooklynNineNine").collection("B99");
  const pizzaDocument = {
    name: "Neapolitan pizza",
    shape: "round",
    toppings: [ "San Marzano tomatoes", "mozzarella di bufala cheese" ]
  };
  const result = collection.insertOne(pizzaDocument);

  // perform actions on the collection object
  //client.close();
});
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Solved it. Needed to put insertOne and client.close() in an async function (thanks @D. SM), like this:

const client = new MongoClient(uri, {
  userNewUrlParser: true,
  useUnifiedTopology: true,
});

async function insert(client) {
  try {
    await client.connect();
    const database = client.db("BrooklynNineNine");
    const movies = database.collection("B99");
    // create a document to be inserted
    const doc = { name: "Red", town: "kanto" };
    const result = await movies.insertOne(doc);
    console.log("Done");
  } finally {
    await client.close();
  }
}
insert(client).catch(console.dir);
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