Storing the mapping reference in an Object within MongoDB using TypeScript

I am currently working with Nest and Mongoose for my project. I need assistance on how to update an object using the FindByIdAndUpdate or FindOneAndUpdate methods. The data is being retrieved from a DTO that utilizes class-validator. In the service layer update method, I am using UpdateQuery to extract data from the controller. This data includes references to other Mongo object IDs as strings.

Could someone please provide guidance on the best approach to updating an object in nest/mongoose? Thank you in advance.

class UpdateProjectDto {
  @IsArray()
  @IsOptional()
  @IsString({ each: true })
  testSuits: [string];
}

class Project{
  @Prop({ type: [MongooseSchema.Types.ObjectId], ref: 'TestSuit' })
  testSuits: TestSuit[];
}

project.service.ts
  async update(
    id: string,
    updateQuery: UpdateQuery<UpdateProjectDto>,
  ): Promise<Project> {
    return this.projectModel
      .findByIdAndUpdate(
        id,
        {
          ...updateQuery,
        },
        {
          new: true,
        },
     )
  }

**Error**
src/projects/controllers/projects.controller.ts:68:50 - error TS2345: Argument of type 'UpdateProjectDto' is not assignable to parameter of type 'UpdateQuery<ProjectDocument>'.
  Type 'UpdateProjectDto' is not assignable to type 'ReadonlyPartial<_UpdateQueryDef<DeepPartial<ProjectDocument>>>'.
    Types of property 'testSuits' are incompatible.
      Type '[string]' is not assignable to type 'DeepPartial<TestSuit>[]'.
        Type 'string' has no properties in common with type 'DeepPartial<TestSuit>'.

68     return await this.projectsService.update(id, updateProjectDto);

Answer №1

If you want to update a project, simply send the UpdateProjectDto directly instead of using the UpdateQuery.

  async updateProject(id: string, updatedData: UpdateProjectDto): Promise<Project> {
    return this.projectModel.findByIdAndUpdate(id, updatedData, {
      new: true,
    });
  }

This method will provide you with the updated project object.

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

Log4j MongoDB experiencing prolonged delay in timeout after 30000ms

I have set up Log4j2 to log information to my Mongo Atlas cluster (version 4.4.8). The configuration appears to be correct (using the connection string provided by Atlas), and the console logs indicate that the connection to MongoDB is successful, with th ...

Resolving type errors in Typescript React Tabs proves to be a challenging task

I am currently in the process of converting a Reactjs Component to a Typescript Component Below is the Tabs Component: <Tabs> <Tab label="one"></Tab> <Tab label="two"></Tab> </Tabs> import React, { ...

The Dynamic Duo: Typescript and Knex

I'm new to TypeScript and currently working on a node application using Express, Postgresql, and Knex. I'm a bit confused about when to apply type definitions in my code. Looking at other projects for guidance has left me even more puzzled as to ...

Retrieve the object property based on an array of indices

I am looking to create a function that can retrieve a specific property of an object based on an array of property names const getObjectProperty = (arr: string[], object: any) { // This function should return the desired object property } Expected Outco ...

Creating an optimized MongoDB structure tailored for a dynamic real-time reporting system

My task involves providing a report on coupon code redemption for a campaign, either hourly, daily, or potentially weekly in the future. Each campaign may have multiple coupon codes. I'm considering using MongoDB and have two possible approaches: T ...

MongoDB failing to return empty objects within documents

I have a JSON snippet within a large MongoDB document: formConfig: { person: {}, title: {name: 'title', ... }, name: {name: 'name', ...} } However, when I try to fetch the document with this JSON, it does not include person: {}. ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

Searching in Mongo DB using a wildcard in the middle of a query, similar to SQL's

This query is quite similar to How to perform a MongoDB search using "like"?. However, I have been unable to utilize that or the resources provided here https://docs.mongodb.com/manual/reference/operator/query/regex/ to construct the necessary query. I am ...

What is the process of setting a TypeScript variable to any attribute value?

I have a variable declared in my TypeScript file public variableName: something; I want to use this variable to replace the value of custom attributes in my HTML code <input type="radio" name="someName" id="someId" data-st ...

MongoEngine does not allow database names to include the character '.'

Attempting to add a document using mongoengine in my python script results in the following exception being raised: (<class 'pymongo.errors.InvalidName'>, InvalidName("database names cannot contain the character '.'",), <trace ...

Issue with Mongoose Model's pre("remove") hook not triggering

I am currently working on implementing a cascading delete hook in my project. The goal is to automatically remove associated records when a user is deleted from MongoDB. While I have been successful in achieving this functionality through manual coding and ...

The autocomplete feature in Atom is not functioning as expected

Autocomplete+ is included with the installation of Atom and is activated by default. I have noticed that when I am coding, no suggestions are appearing. What could be causing this issue? Do I need to adjust any files in order for Autocomplete+ to functio ...

Utilizing Provide/Inject in Vue 3 Typescript to retrieve a method within a component, encountering the possibility of an 'undefined' Error Object

Having trouble calling the loginWithRedirect function within the header.vue component using inject feature in Vue 3 and Typescript. ERROR in src/components/global/HeaderMenu.vue:77:17 TS2339: Property 'loginWithRedirect' does not exist on type ...

Is there a way to fetch a unique row count from a particular column in a Mongo DB collection using a Laravel REST Api controller?

I am currently working on a React-based web application supported by a Laravel REST API on the back-end. The task at hand requires me to fetch and display the count of a specific column in a database collection, which will then be shown on the dashboard. T ...

encountered difficulty in fetching information from mongoDB

I have successfully created user accounts and stored them in a MongoDB users database within a users collection. To validate that the users are indeed stored, I am utilizing Studio 3T. Within my dal.js file, I have implemented the code responsible for retr ...

Encountering InvalidOperationException when using AsQueryable in C# for querying operations

In my code, I have defined an entity class called City. [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)] public string _id { get; set; } public string city { get; set; } public Array loc { get; set; } public double po ...

Tips for executing a query that involves verifying a Boolean property

Directory files: {"_id":"5d1e2da512ad38225af60869","id":1,"name":"email","necessary":true} {"_id":"5d1e2da512ad38225af6086b","id":2,"name":"sent","necessary":true} {"_id":"5d1e2da512ad38225af6086d","id":3,"name":"archived","necessary":true} {"_id":"5d1e2d ...

Retrieve the summary of records in MongoDB database

In my 'tickers' collection, the data is formatted like this: { "_id": ObjectId("50d192b5480cf44157000000"), "ticker": { "high": 13.38839, "low": 13.1225, "avg": 13.244705635, "vwap": 13.258414151, "vol": NumberInt(21562), ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...