Reputation: 469
I am seeing my mongoose pool seemingly close before it inserts data as I am getting this error when making a call to my mongoose db in my cloud cluster
MongoRuntimeError: Connection pool closed
but I am awaiting all of the calls? so I'm unsure why I'm seeing this issue, maybe it has something to do with the way I am defining my client? hopefully someone has some tips or ideas on this
export const storeData = async (data) =>{
const uri = `mongodb+srv://plantmaster:${password}@cluster0.yey8l.mongodb.net/plantstore?retryWrites=true&w=majority`;
const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1
});
const newPLantData = { name: "Company Inc", address: "Highway 37" };
await client.db("plantstore").collection("plantdata").insertOne(newPLantData, (err, res) =>{
if(err) throw err;
console.log(result)
})
await client.close();
};
I am calling this function on an express post route like so
// store data
app.post('/store', async function (req, res) {
await storeData(req.body);
res.send('data was stored')
})
Upvotes: 4
Views: 7394
Reputation: 7
Try this example approach
import { MongoClient } from "mongodb";
const handler = async (req, res) => {
if (req.method === "POST") {
const { email } = req.body;
if (!email || !email.includes("@")) {
res.status(422).json({ message: "Entered email is not valid" });
return;
}
const url = <your-mongo-url>
const client = new MongoClient(url);
await client.connect();
const collection = client.db("events").collection("newsletter");
try {
await collection.insertOne({ email });
return res.status(201).json({
message: "You have successfully signed up to newsletters!",
email,
});
} catch (error) {
throw res.status(500).json({ message: "Server error occured" });
} finally {
client.close();
}
}
};
export default handler;
Upvotes: 0
Reputation: 96
i was facing the same error, but i fixed it by waiting 1500ms before closing the connection.
setTimeout(() => {client.close()}, 1500)
Upvotes: 8