An issue I am encountering: *CastError: Cast to string failed for value "[ 'ZTM', 'NASA' ]" (type Array) at path "customers" at model.Query.exec (/Users/mike/Documents/NodeJS-applications/NASA-project/server/node_modules/mongoose/lib/query.js:4891:21) at model.Query.Query.then (/Users/mike/Documents/NodeJS-applications/NASA-project/server/node_modules/mongoose/lib/query.js:4990:15) at processTicksAndRejections (node:internal/process/task_queues:96:5)
{
messageFormat: undefined,
stringValue: "[ 'ZTM', 'NASA' ]"
,
kind: 'string',
value: [ 'ZTM', 'NASA' ],
path: 'customers',
reason: null,
valueType: 'Array'
}
The above error is related to mongoose, and it seems to stem from an inconsistency in the customers field defined in the schema, which should be an array of string objects.
Below is the relevant code snippet:
import { getModelForClass, prop, Ref, index } from "@typegoose/typegoose";
import * as mongoose from "mongoose";
import { Planet } from "./planets.typegoose";
@index({ flightNumber: 1 })
class Launch {
@prop({ type: () => Number, required: true })
public flightNumber: number;
@prop({ type: () => Date, required: true })
public launchDate: Date;
@prop({ type: () => String, required: true })
public mission: string;
@prop({ type: () => String, required: true })
public rocket: string;
@prop({ ref: () => Planet, required: true })
public target: Ref<Planet, mongoose.Types.ObjectId>;
@prop({ type: () => [String], required: true })
public customers?: string[];
@prop({ type: () => Boolean, required: true })
public upcoming: boolean;
@prop({ type: () => Boolean, required: true, default: true })
public success: boolean;
}
const LaunchModel = getModelForClass(Launch);
export default LaunchModel;
This defines the structure and type for the launch interface:
interface LaunchType {
flightNumber?: number;
mission: string;
rocket: string;
launchDate: Date;
target: string;
customers?: string[];
upcoming?: boolean;
success?: boolean;
}
Create a launch object with the type annotation "LaunchType":
const launch: LaunchType = {
flightNumber: 100,
mission: "Kepler Exploration Soran",
rocket: "Saturn IS2",
launchDate: new Date("December 27, 2030"),
target: "kepler-442 b",
customers: ["ZTM", "NASA"],
upcoming: true,
success: true,
};
Function: To save this launch object to MongoDB collection:
async function saveLaunchToMongoDB(launch: LaunchType): Promise<void> {
await LaunchModel.updateOne(
{
flightNumber: launch.flightNumber,
},
launch,
{ upsert: true }
);
}
I can successfully save the launch object to the MongoDB collection without any errors when I remove the customers property of type string[] from the schema, interface, and the launch object.
The issue may lie in the discrepancy between the customers property being a type of string[] or undefined (union type) in the interface, while in the schema it is set to return a string constructor.