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

544
Views
"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 answers
Answer question

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 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!