Q: "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):

*

*Changing my password for the user to only letters (no numbers or symbols)

*Removing client.close(); at the end.

*Reformatting my code as shown below (got the "format" from another post).

*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();
});


A: 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);

