The issue arose when attempting to save a nested list of schema types in Typegoose and Mongoose, resulting in a failed Cast to

Encountering this issue:

Error: Competition validation failed: results.0: Cast to ObjectId failed for value "{ name: 'David'}"

The main model is as follows:

class Competition {
  @prop()
  compName: string
  

  @prop({ ref: () => CompetitionParticipant})
  results: Ref<CompetitionParticipant>[]
}

And the sub-model looks like this:

class CompetitionParticipant  {

  @prop()
  name: string
}

This is how it's being utilized:

const CompetitionResults = getModelForClass(Competition)
await new CompetitionResults({compName: 'competition name', results: [{name: 'David'}]}).save()

Answer №1

the reason why you encounter this issue is due to attempting to store the value { name: 'David' } as a reference, which is not supported (find out more here). Instead, you must either provide a valid _id (such as an ObjectId), or an instance of mongoose.Document

one workaround is to manually iterate through the array and save each item individually (similar to a bulk-insert operation, or by using a for loop to go over each element in the 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

Dynamically incorporate new methods into a class

Currently, I am in the process of implementing setters and getters for items that will be stored in session storage. These methods are being written within a service. However, upon attempting to call these functions in my component, I am encountering a tra ...

Having trouble establishing a connection between the webservice and mongodb

I've developed an Android application that performs SOAP requests to my Tomcat server. The server hosts a web service (MongoService.wsdl) which calls another class (DataLayer.java) containing a static method (getConnection). However, the initializatio ...

What is the process for using infer to determine the return type of a void function?

I am trying to gain a better understanding of how to utilize the infer keyword in TypeScript. Is this an appropriate example demonstrating the correct usage of infer? I simply want to infer the return type of the function below: const [name, setName] = u ...

Cannot compile Angular 4 Material table: Encountering unexpected closing tag

Currently, I am working on an Angular 4 Project that involves using Material. The main task at hand is to implement a table from Angular Material. However, the issue I am facing is that the table does not compile as expected. Here's the HTML code sni ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Encountering issues with inserting documents into a MongoDB collection using the Java driver

I am currently working with MongoDB using the mongo-java-driver version 2.11.2. I have been trying to insert some documents into my database using MongoDB command line and it works perfectly fine. However, when I attempt to do the same using the mongo-java ...

Testing a React component that utilizes RouteComponentPropsTesting a React component with RouteComponentProps

One of my components has props that extend RouteComponentProps defined as follows: export interface RouteComponentProps<P> { match: match<P>; location: H.Location; history: H.History; staticContext?: any; } When I use this component i ...

Unable to send an API request from Postman to a database through express and mongoose technology

This is my server.js: const express= require('express'); const app = express(); // const mongoose= require('mongoose'); // load config from env file require("dotenv").config(); const PORT = process.env.PORT || 4000; // middl ...

Combining two fields to group and aggregating the fields from nested documents in MongoDB

Looking to utilize the aggregate function to group documents by two fields, sum a value within an embedded document, and then identify the highest and lowest values. The grouping should be based on Company & Date. We need to sum up the stock volume f ...

Working with <html> response data in place of Json in Angular 6

My Angular 6 application needed to call a web service that returns HTML data, which I then had to display within a div. Below is an example of the HTML response data from the service: <html> <head> <title>Chart : 180: Abraham, Male, 1 ...

How to verify the existence of an object property in typescript

I am dealing with a queryParams object that I need to use to query the database based on its properties. However, I am unable to determine which parameters it contains. I attempted to utilize find(queryParameters: object = { limit: 50 }){ if (queryParamete ...

Exploring the differences between arrays and filter functions within MongoDB aggregation operations

Recently, I crafted a sophisticated pipeline for my database: let orders = await Order.aggregate( { $unwind: "$candidate", }, { $lookup: { from: "groups", localField: & ...

Implementing a Single handleChange Event for Multiple TextFields

How can I use the same handleChange event for multiple TextFields in React? import * as React from "react"; import { TextField} from 'office-ui-fabric-react/lib/TextField'; export interface StackOverflowState { value: string; } export de ...

Tips for narrowing down the type of SVG elements in a union

In my React project, I am facing an issue where I need to set a reference to an svg element that could be either a <rect>, <polygon>, or <ellipse>. Currently, I have defined the reference like this: const shapeRef = useRef<SVGPolygon ...

Issue with absolute import in React TypeScript application

An error occurs when trying to import a module, displaying the following message: Compiled with problems: × ERROR in ./src/App.tsx 5:0-33 Module not found: Error: Can't resolve 'routes' in 'F:\Tamrinat\Porfolio\microsite ...

What is the process of connecting tags to messages and users within a messaging application?

As I develop an app that utilizes a MongoDB database for messaging between two individuals, my goal is to implement a feature allowing each user to create and assign tags to messages. The idea is for users to have the flexibility of adding new tags or sele ...

Retrieve data from a MongoDB object without prior knowledge of the object key

I currently have this data stored in my database { "_id":"606b583b2506eb000988a8fd", "lastSync":"2021-04-13T00:10:02.984+00:00", "Month":{ "2020-12":{ "a":10, "b&quo ...

utilizing if statements to call upon the correct phases in collections

Below is a concept of an ideal syntax that I wish existed so I could easily fetch sessions from my Course collection. Each course in the collection has a sub-document array called sessions. I aim to retrieve courses based on user query parameters when sear ...

Experimenting with setting up ReactiveMongoTemplate in a Java environment

In my Java/Spring project, I am implementing ReactiveMongoTemplate to establish a connection with a database. What is the best approach to verify if the connection between the application and the database is set up correctly to enable data insertion? Addi ...

Connections to MongoDB Atlas clusters are consistently limited

I have set up an express server with mongoose and MongoDB Atlas for the backend. The application is currently hosted on heroku. The database connection is established only once during server startup: db() .then(() => { console.log('Connected ...