I am trying to send a POST request using Postman but getting a CastError.
Why can’t I just send the patient and provider fields as strings? Is this the documentation I should be looking at?
I’ve seen solutions, but my server crashes. Here are two:
const id = mongoose.Types.ObjectId(req.body.patient)
or
import { ObjectId } from "mongodb";
const convertedId = ObjectId(req.body.patient)
This is the request I am trying to send:
{
"patient": "StackOverFlow",
"provider": "MariaMorales",
"startTime": "1660572900250",
"endTime": "1660573800250"
}
The error:
{
"message": {
"errors": {
"patient": {
"stringValue": ""StackOverFlow"",
"valueType": "string",
"kind": "ObjectId",
"value": "StackOverFlow",
"path": "patient",
"reason": {},
"name": "CastError",
"message": "Cast to ObjectId failed for value "StackOverFlow" (type string) at path "patient" because of "BSONTypeError""
}
},
"_message": "Appointment validation failed",
"name": "ValidationError",
"message": "Appointment validation failed: patient: Cast to ObjectId failed for value "StackOverFlow" (type string) at path "patient" because of "BSONTypeError""
}
}
Models:
import mongoose, { Schema } from 'mongoose';
export interface isAppointment {
// patient: string;
// provider: string;
startTime: Date;
endTime: Date;
}
const AppointmentSchema: Schema = new Schema({
patient: { type: Schema.Types.ObjectId, ref: 'Patient' },
provider: { type: Schema.Types.ObjectId, ref: 'Provider' },
startTime: { type: Date, required: true },
endTime: { type: Date, required: true }
});
export default mongoose.model<isAppointment>('Appointment', AppointmentSchema);
import mongoose, { Schema } from 'mongoose';
export interface isPatient {
_id: string;
name: string;
surname: string;
}
const PatientSchema: Schema = new Schema(
{
_id: { type: String, required: true },
name: { type: String, required: true },
surname: { type: String, required: true }
},
{ timestamps: true }
);
export default mongoose.model<isPatient>('Patient', PatientSchema);
The Controller Fnc:
import { Request, Response, NextFunction } from 'express';
import Appointment from '../models/Appointment';
const createAppointment = async (req: Request, res: Response, next: NextFunction) => {
try {
const appointment = new Appointment(req.body);
await appointment.save();
return res.status(200).json(appointment);
} catch (error) {
res.status(500).json({ message: error });
}
};
export default { createAppointment };
2
Answers
Take a look at
objectId
documentation.ObjectId – MongoDb
You can not cast a string to ObjectId if it is not hexadecimal. So, you can not save stack overflow as your ObjectId.
To generate a valid ObjectId use the code below:
Because I had overwritten the _id property of my patient and provider models to
String
, I needed to reference their type. Thanks, Pooya Raki!Answer: