Home > Mobile >  Trying to send POST request with Postman but getting CastError
Trying to send POST request with Postman but getting CastError

Time:08-16

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 };

CodePudding user response:

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:

const generateObjectId = require('mongodb').ObjectID;

const objectId = new generateObjectId();

CodePudding user response:

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:

const AppointmentSchema: Schema = new Schema(
    {
        patient: { type: Schema.Types.String, ref: 'Patient' },
        provider: { type: Schema.Types.String, ref: 'Provider' },
        startTime: { type: Date, required: true },
        endTime: { type: Date, required: true }
    },
    { timestamps: true }
);
  • Related