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):
client.close(); at the end.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();
});
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);