What could be causing the Postman socket to hang up even when my connection to the database is established?

Currently, I am working on an Express/TypeScript API and my goal is to create a new patient using Postman. I have made sure to provide all the necessary properties as per the EmrPatient model file listed below:


import mongoose from 'mongoose'

// # 1. Creating a Patient - EmrPatientAttrs Interface
interface EmrPatientAttrs {
  emrId: string
  clinicId?: string | number
  patientId: string | number
  doctorId: string | number
  firstName: string
  lastName: string
  gender: string
  dob: string
  address?: string
  city?: string
  state?: string
  zipCode?: number
  alunaPatientId?: string | number
  alunaDoctorId?: string | number
}

// # 2. Entire Collection of Patients - EmrPatientModel Interface
interface EmrPatientModel extends mongoose.Model<EmrPatientDoc> {
  build(attrs: EmrPatientAttrs): EmrPatientDoc;
}

// # 3. Properties of a Single User - EmrPatientDoc Interface
interface EmrPatientDoc extends mongoose.Document {
  // Properties...
}

const emrPatientSchema = new mongoose.Schema(
  // Schema details...
);

emrPatientSchema.statics.build = (attrs: EmrPatientAttrs) => {
  return new EmrPatient(attrs);
};

const EmrPatient = mongoose.model<EmrPatientDoc, EmrPatientModel>('EmrPatient', emrPatientSchema);

export { EmrPatient }

This is the specific route I'm trying to execute:


import express, { Request, Response } from 'express'
import { EmrDoctor } from '../models/EmrDoctor';
import { EmrPatient } from '../models/EmrPatient';
import { DatabaseConnectionError } from "../middlewares/database-connection-error";

const partnerRouter = express.Router()

partnerRouter.post('/api/v3/partner/patients', async (req: Request, res: Response) => {
  console.log("Creating a patient...");
  throw new DatabaseConnectionError();
});

It seems like everything in my code is correct; however, there seems to be an issue that I can't pinpoint. The expected outcome should be a status of 201 Created.

Here is the JSON data used in Postman:

[
    {
        "emrId": "123", 
        "patientId": "abc", 
        "doctorId": "196", 
        "firstName": "Harry", 
        "lastName": "Smith", 
        "gender": "male", 
        "dob": "March 31, 1990"
    }
]

After incorporating better error handling within the program, it seems like the problem lies with the database connection. Despite receiving a confirmation message stating successful connection upon starting the app, it fails to establish a connection during actual execution:


import express from "express";
import { json } from "body-parser";
import mongoose from "mongoose";
import { partnerRouter } from "./routes/partner-routes";
import { errorHandler } from "./middlewares/error-handler";

const app = express();
app.use(json());

app.use(partnerRouter);

app.use(errorHandler);

const start = async () => {
  try {
    await mongoose.connect("mongodb://127.0.0.1:27017/auth", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    });
    console.log("Connected to MongoDB");
  } catch (error) {
    console.log(error);
  }
  app.listen(3000, () => {
    console.log("Listening on port 3000!");
  });
};

start();

Answer №1

When modifying your mongoose.connect, it is important to remove the arguments that are now deprecated. Refer to this link for more information. Make sure your code looks like this:

try {
    await mongoose.connect("mongodb://127.0.0.1:27017/auth");
    console.log('Connected to database');
  } catch (err) {
    console.error(err);
  }

In addition, ensure that you include a response in your create patient post method. Instead of throwing an error, use res.json({}) or res.send().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting a default value for the dropdown in Angular is essential for ensuring a smooth

<select [(ngModel)]="detail.State" (ngModelChange) ="onStateChange()" class="form-control"> <option [ngValue]="null" disabled selected>Select State</option> <option * ...

TS2339: The object of type 'Y' does not contain a property named 'x'

Confusion arises as to why the TypeScript error is triggered in this piece of code. (Please disregard the irrelevant example given): interface Images { [key:string]: string; } function getMainImageUrl(images: Images): string { return images.main; } E ...

Creating dynamic pages using user input in Node and Express

Currently, I am facing a challenge in rendering text using node/express. Within my project setup, there is an HTML file containing a form. The file named search.ejs looks like this: $(document).ready(function(){ var userInput; $("#submit-button-i ...

Issue Establishing Connection Between Skill and Virtual Assistant Via Botskills Connect

Encountering errors while connecting a sample skill to a virtual assistant. Both are in typescript and function individually, but when using botskills connect, the following errors occur: Initially, ran botskills connect with the --localManifest parameter ...

Ways to extract additional information beyond just the 'Webpack Compilation Error' while using Cypress

Every time an error occurs in one of my imported modules, Cypress only provides the vague message Error: Webpack Compilation Error. It's frustrating not to have a useful error stack to troubleshoot the issue. Is there a way to access more detailed err ...

Can you explain the concept of widening in relation to function return types in TypeScript?

Recently, I've observed an interesting behavior in TypeScript. interface Foo { x: () => { x: 'hello' }; } const a: Foo = { x: () => { return { x: 'hello', excess: 3, // no error } }, } I came acro ...

Is it possible to integrate gsap or anime.js with Angular 7? If so, what is the process for doing so?

After attempting to install Gsap using npm install gsap, I've run into some issues where it's not functioning as expected. Could you provide guidance on how to effectively utilize gsap in an angular 7 environment? My goal is to incorporate animat ...

Create a d.ts file in JavaScript that includes a default function and a named export

While working on writing a d.ts file for worker-farm (https://github.com/rvagg/node-worker-farm), I encountered an issue. The way worker-farm handles module.exports is as follows: module.exports = farm module.exports.end = end When trying to replica ...

The mongodb $or operator consistently evaluates to false (constant)

I created an aggregation pipeline to retrieve documents and add a new field called "expired" (boolean), where its value is determined by the "expireAt" (Date) field. The "expired" field will be considered true if: expireAt is missing, null, or empty exp ...

Creating a JSON object from an array of data using TypeScript

This might not be the most popular question, but I'm asking for educational purposes... Here is my current setup: data = {COLUMN1: "DATA1", COLUMN2: "DATA2", COLUMN3: "DATA3", ..., COLUMNn: "DATAn"}; keyColumns = ["COLUMN2", "COLUMN5", "COLUMN9"]; ...

The page has been updated following a refresh

I'm currently working on developing an Instagram-inspired platform using Angular 6, but I've run into a puzzling issue. When I refresh the page in my home component, everything reloads correctly and displays all my posts as expected. However, if ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

Guide to Making a Cookie Using Node's cookie-session Package

I'm currently working on a small node application and my goal is to have it create a cookie for every visitor, named 'session', which will store the session ID. However, I've been facing some challenges in getting node to generate this ...

Querying mongoose with $near or other fields

I'm trying to retrieve documents using a query $or on different fields along with a $near query that is causing issues. Schema locationSchema{ ... beacon: String, access_point: String, gps: [], ... } locationSchema.index({ gps: ...

What is the best way to programmatically define the value for the MaterialUI grid size property using TypeScript?

Is there a way to dynamically pass a value to the Grid size props like XL in TypeScript? For instance, *Update for further clarification import Grid, { GridSize } from "@material-ui/core/Grid"; let value: GridSize = 12/4; xl={value} Error: Type &apos ...

Update my SPFx web component to link to a CSS file instead of embedding the CSS styles directly within the component

I recently developed a web part that is reminiscent of a similar one found on GitHub @ https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-enhanced-list-formatting. This particular web part enables the embedding of custom CSS code directly in ...

The Microsoft Bing Maps V8 TypeScript library is unable to load: "Microsoft is not recognized."

I'm looking to integrate BingMaps into my React project using TypeScript. After installing the npm bingmaps package, I have included the necessary d.ts file. To import the module, I use the following code: import 'bingmaps'; Within my Com ...

Different ways to determine if a given string exists within an Object

I have an object called menu which is of the type IMenu. let menu: IMenu[] = [ {restaurant : "KFC", dish:[{name: "burger", price: "1$"}, {name: "french fries", price: "2$"}, {name: "hot dog", d ...

How to pass model from NodeJS and ExpressJS to Knockout using Jade?

Currently, I am facing a challenge in passing my expressJS Model to my .jade template while trying to access the Model using JavaScript on the client-side. The concept is straightforward: I am looking to utilize the Model with Knockout.js, therefore requi ...

Angular error: The function redirectToLogin in src_app_app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule is not defined

I'm attempting to redirect users from the homepage to the login page using home.component.ts. Within this file, I've invoked a static method called "AppRoutingModule.redirectToLogin()" that I've defined in app-routing.module.ts by importing ...