skip to Main Content

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


  1. Use await to wait for query to complete .

    const result = await db.collection('users').insertOne(newUser);
    
    Login or Signup to reply.
  2. 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:

    const { MongoClient } = require('mongodb');
    
    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, { useNewUrlParser: true, useUnifiedTopology: true });
    
        try {
            await client.connect();
            const db = client.db();
            const result = await db.collection('users').insertOne(newUser);  // Await the insert operation
            res.json(newUser);  // Send the response after successful insertion
        } catch (error) {
            console.error('Error inserting data:', error);
            res.status(500).json({ message: 'Could not store data' });  // Send error response
        } finally {
            await client.close();  // Ensure the client is closed in the finally block
        }
    };
    
    exports.createUser = createUser;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search