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();