I’m trying to test out a post request on Postman to 3000/users and I’m getting the 200 but is not reflected on Mongo and I’m getting an error in the console saying server has been closed.
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb+srv://url-here'
const createUser = async (req, res, next) => {
const newUser = {
name: req.body.name,
username: req.body.username,
password: req.body.password
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection('users').insertOne(newUser);
} catch (error) {
return res.json({message: 'Could not store data'});
};
client.close();
res.json(newUser);
};
exports.createUser = createUser;
exports.getUsers = getUsers;
app.js:
const express = require('express');
const bodyParser = require('body-parser');
const mongoPractice = require('./config/db');
const { mongo } = require('mongoose');
const app = express();
app.use(bodyParser.json());
app.post('/users', mongoPractice.createUser);
app.listen(3000);
But I’m getting this error in the console:
C:UsersUsercodingts-trainingsnode_modulesmongodblibsdamserver.js:133
throw new error_1.MongoServerClosedError();
^
MongoServerClosedError: Server is closed
at Server.command (C:UsersUsercodingts-trainingsnode_modulesmongodblibsdamserver.js:133:19)
at InsertOneOperation.executeCommand
(C:UsersUsercodingts-trainingsnode_modulesmongodbliboperationscommand.js:74:29)
at InsertOneOperation.execute (C:UsersUsercodingts-trainingsnode_modulesmongodbliboperationsinsert.js:37:28)
at InsertOneOperation.execute (C:UsersUsercodingts-trainingsnode_modulesmongodbliboperationsinsert.js:46:33)
at executeOperation (C:UsersUsercodingts-trainingsnode_modulesmongodbliboperationsexecute_operation.js:136:32) at process.processTicksAndRejections
(node:internal/process/task_queues:95:5)
at async Collection.insertOne (C:UsersUsercodingts-trainingsnode_modulesmongodblibcollection.js:155:16) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.12.1
I can’t seem to figure out why the server is closing before action has been completed. Thank you in advance for your help.
2
Answers
Use await to wait for query to complete .
The issue arises because the client.close() method is being called before the insertOne operation has completed. The insertOne method is asynchronous, and you’re not awaiting it, causing the client to close prematurely.
Here’s the corrected version of your createUser function with the necessary changes:
Await the insertOne operation: Ensure that you await the completion of the insert operation before closing the client connection.
Proper error handling and response: Ensure that the response is sent back to the client even if an error occurs.
The updated code is given below: