Mongoose encountered an error when attempting to cast the value "ObjectID" to an ObjectId at the specified path "red.s1"

My Mongoose schema is structured as follows:

const gameSchema = new Schema({
    matchNumber: {
        type: Number,
        required: [true, 'A match must have a number!'],
        unique: true
    },
    red: {
        s1: {
            type: ObjectId,
            ref: 'Match'
        },
        s2: {
            type: ObjectId,
            ref: 'Match'
        },
        s3: {
            type: ObjectId,
            ref: 'Match'
        }
    }
});

I am attempting to update the document with a Match through Express. When making a POST request to

:matchNumber/:alliance/:seed/:teamNumber/match
, I execute the following logic:

import * as flatten from 'flat';

let match = req.body;
const game = await Game.findOneAndUpdate(
    { matchNumber },
    flatten({ [alliance]: { [seed]: match._id } }),
    { new: true }
);

However, upon sending the POST request, I receive the error message:

CastError: Cast to ObjectId failed for value "ObjectID" at path "red.s1"

It's worth noting that I am working with TypeScript and while this code was partially functional before, I came across some issues similar to those discussed here. The suggested solution to those problems seems to have caused the current error I am facing.

Answer №1

I successfully resolved the issue by eliminating the flat package and adjusting it to this new format:

const loc = `${alliance}.${seed}`;
const game = await Game.findOneAndUpdate(
    { matchNumber },
    { $set: { [loc]: match._id } },
    { new: true }
);

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

What is the process for removing a document with the 'where' function in Angular Fire?

var doc = this.afs.collection('/documents', ref => ref.where('docID', '==', docID)); After successfully retrieving the document requested by the user with the code above, I am unsure of how to proceed with deleting that do ...

The present time lags behind in nodejs by a 6-hour difference

I want to compare the current datetime with the datetime stored in a database column. When I use new Date() on my computer, it gives me datetime as 2023-05-21T04:35:07.903Z, even though my computer time shows 10:35:07. How can I resolve this issue? Please ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

Challenge with module declaration in index.d.ts during upgrade from Angular 8 to 9 (excluding Material)

In my index.d.ts file, I have declared two modules like so: declare module 'googlemaps'; declare module 'detect-resize'; Previously, these declarations worked perfectly fine, allowing me to utilize these modules. The googlemaps module ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Angular Component Test Results in TypeError Error Failure

After defining a custom error class called CustomError: export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } } I want to throw instances of ...

Utilize an array of observables with the zip and read function

I'm struggling with putting an array of observables into Observable.zip. I need to create a function that reads values from this dynamically sized array, but I'm not sure how to go about it. Does anyone have any suggestions? import {Observable} ...

Tips for updating specific properties of an object within a MongoDB database using arrays

I have encountered a problem with updating only specific properties of an object in my MongoDB database. While the query I'm using is working for most variables, it unexpectedly sets certain arrays (media: [] and sports: []) in the athleteProfile back ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...

Unable to globally override the default font in MUI theme

Objective: My goal is to customize the default font in MUI themes. Issue: Despite reviewing MUI documentation and conducting research on Stack Overflow, I am facing difficulty overriding a custom font globally across my theme. Theme setup: import { creat ...

How can we efficiently link data to custom objects (models) within a different class while fetching data from the server using the http.get() method in Angular CLI?

Currently in the process of developing an Angular-Cli application that involves multiple models with relational data tables. When fetching data from the server, I need to map this data to corresponding model objects. I've experimented with creating a ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Issue with Next.js: Router.push not causing page to refresh

I'm currently developing a next.js page called /page/data/[dataId] (this page is accessed when a user clicks on a link from the page /page/data, where I fetch the list of items through an API). When a user clicks on a button, I make an API call to de ...

Recommendation on utilizing API Access using Express-Gateway and implementing User authentication with JWT

I have a server in Express that exposes some APIs to a web application. I am exploring options for managing authentication for both end-users and third-party entities. Currently, when a user signs up with email and password, the server creates a JWT toke ...

Using TypeScript to specify data types in the Vue data object

I am currently utilizing Vue.js with Typescript in a webpack project. Following the guidelines provided in the Recommended Configuration in my tsconfig.json, I have set: "strict": true, Within one of my components, I have: declare interface P ...

Utilizing flatMap to implement nested service calls with parameters

Recently, I encountered an issue while working on a service call to retrieve data from a JSON file containing multiple items. After fetching all the items, I needed to make another service call to retrieve the contents of each item. I tried using flatMap f ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

Sending POST Requests with Next.js Version 14

How can I send a POST request using axios in Next.js 14, I prefer axios but fetch is also okay. I have been getting an AxiosError: Network Error when I try to use axios and TypeError: fetch failed when using fetch. However, it works fine with Postman. I ...

Content Security Policy prevents videos from loading in React applications

I'm encountering an issue while attempting to showcase a video preview within my React application. The error message states: "Refused to load media from 'data:video/mp4;base64,...' because it violates the following Content Security Policy ...