The CastError occurred because the attempt to add a string value to an array failed when converting it to a string

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.

Answer №1

To convert the customer type from [String] to an Array, you can do the following:

@prop({ type: () => Array, required: true })
public customers? Array;

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

Building an Event Scheduler in Outlook Calendar with Angular 5

Currently, I am utilizing Angular version 5.2 for a room booking portal project. One of the requirements entails adding an event to the Outlook calendar on the day a room is booked. The system includes a table listing all bookings, with a button in each ro ...

Exploring Angular 12: utilizing rxjs observables with chained subscriptions for enhanced functionality and robust error handling

Can someone help me with creating a function that I can subscribe to, returning: an observable containing the result if all operations were successful an observable with an empty string in all other scenarios foo(): void { this.uploadImage.subscr ...

What are the steps to properly update information in a mongo database?

I am currently immersed in a project involving mongodb and nodejs, and I find myself pondering: How can one update data in mongodb using nodejs? Specifically, my challenge lies in wanting to retain the existing data while adding new information. For instan ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

Attempting to extract information from mySQL and convert it into a PHP array

Lately, I have dedicated my time to a project. In this project, I have set up a database which stores various elements like id, title, imgUrl, intro, and content. My goal is to fetch this data from the MySQL database and organize it into a PHP array as dep ...

Finding the positions of elements that exist in a separate list using numpy

I need assistance with finding the indices of elements in the first numpy array that also exist in the second array. Here is an example: import numpy as np x = np.array([0,1,1,2,3,4,5,5]) y = np.array([1,3]) # I want to obtain np.array([1,2,4]) If y was ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

Loop through a collection of arrays that contain the same elements, and multiply each consecutive element by a specified value x

I've been diving into a challenging problem involving remarkable numbers, which are defined as A number that is equal to the sum of all its proper divisors -- provided one of them is negative. For instance, the proper divisors of 12 are 1, 2, 3, 4, 6 ...

Updating the address array within the data object's state

Hello, I'm currently delving into React and working on an app with the MERN stack. I could really use some guidance. Within my React User component, I am rendering a user object with embedded documents from mongodb. The data returned from the databas ...

Facing an error stating "sonata.user.mongodb.user_manager" does not exist while integrating Symfony2 with Sonata UserBundle, FOS UserBundle, and MongoDB

Trying to integrate Sonata/UserBundle with MongoDB, I've encountered an issue that is causing trouble. An error message popped up, looking quite ugly: The service definition for "sonata.user.mongodb.user_manager" appears to be missing. Below is th ...

Querying MongoDB to analyze data using map-reduce to extract values from the most recent record for

I need to gather data on the authors of Twitter posts using the most recent information available. Within a set of Twitter posts, I am looking to extract details from the most recent post by each author - specifically, I am interested in obtaining the fri ...

Implement and remove changes in mongodb

My database sample looks like this: db={ "sample": [ { current_book: "Aurthor", upcoming_book: [ "Sigma", "Rocky" ] } ] } I am trying to update the current_book value to ...

Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Da ...

Performing a search on a MongoDB collection using the $all operator on an array that contains no elements will not yield any

When I execute a query on my MongoDB server using $all with an empty array filter, I am not receiving any results. Currently, I am using pymongo for querying. Specifically, when my filter looks like this: my_collection.find({"some_field": some_value, "ar ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

Transform an array containing arrays into an array of individual objects

After spending a considerable amount of time trying various solutions, I am still unable to achieve the desired result. The issue lies in getting an array of objects from service calls and organizing them into a single array for data loading purposes. The ...

Error: Observable<any> cannot be converted to type Observable<number> due to a piping issue

What causes the type error to be thrown when using interval(500) in the code snippet below? const source = timer(0, 5000); const example = source.pipe(switchMap(() => interval(500))); const subscribe = example.subscribe(val => console.log(val)); V ...

Creating an interface in Dart: Step-by-step guide to defining interfaces similar to TypeScript

Coming from a Typescript background, I used to define object interfaces like this: export interface Locale { login: { title: string; actions: { submit: string; forgot: string; } } } However, in Dart, interfaces are implicit an ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

How can one in C add the length of a fixed string to the beginning of the string in a static manner, similar to BCPL?

One idea I have for handling static field names is to use C compiler magic to dynamically prepend the length of the field name. For example, instead of storing "LABEL" at compile time, it would store "\x05LABEL". (Those familiar with BCPL may remember ...