I have a Node/Express server communicating with MongoDB. Below is my initial function which I call whenever I want data from the database:
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('database-name');
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error });
}
}
When I want to fetch, add, or edit some data I use:
app.get('/api/employees', async (req, res) => {
withDB(async (db) => {
const tabInfo = await db.collection('users').find().toArray()
res.status(200).json(tabInfo);
}, res);
});
I have several of these operations performing CRUD operations, and all work fine, but for some reason this particular one above is causing an intermittent error:
res.status(500).json({
^
TypeError: Cannot read properties of undefined (reading 'status')
I haven't yet been able to isolate when this error occurs? That fetch request is only called on one page of my React app, and I can't make the server crash.
Does anyone have any suggestions as to how I can handle the error correctly to prevent the server crashing, or a system to automatically restart the server when it does?