Issue when attempting to access a nested object in console.log within NestJS. The error message reads: "Property x does not exist on type Dto

Struggling to get the nested object to display in my console log for the past day. Here's the JSON I'm working with:

{
   "data": {
      "assets": [
              {
                 "asset_name": "Image1.jpg",
                 "asset_type": "photo",
                 "is_featured": true,
                 "asset_id": "alksjd78987120-kjahsdkjahsd61238-kjahsdkjahsjkdh",
                 "action": "delete"
              },
              {
                  "asset_name": "Image2.jpg",
                  "asset_type": "photo",
                  "action": "add"
              }
       ]
     }
   }

Attempting to display console.log(data.assets); from my controller file, but encountering the error

Property 'assets' does not exist on type 'DataDto'.

Here is my DataDto.ts:

export class CreateAssetsDto {
   @IsString()
   @IsOptional()
   asset_id: string;

... (skipping rest of the code for brevity) ...

export class DataDto {
   @ValidateNested()
   @Type(() => AssetsArrayDto)
   data: AssetsArrayDto;
}

Examining this snippet from my controller.ts:

@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'))
@UsePipes(new ValidationPipe({ transform: true }))
@Put(':id')
async uploadAssets(
   @Request() req,
   @Param('id') campaignId: string,
   @Body() data: DataDto) {
   try {
     console.log("Data Check");
     ... (skipping logging and parsing code) ...
     return {
       statusCode: HttpStatus.OK,
       message: data,
     };

   } catch (error) {
     Logger.log('Validation Error: ');
     Logger.log(error);
     throw new BadRequestException(error);
   }
 }
 }

Am I missing something here? It appears that assets are not being read as part of my data object despite being defined in the DTO.

When I do console.log(data), the output is:

Data Check
DataDto {
 data: AssetsArrayDto { assets: [ [CreateAssetsDto], [CreateAssetsDto] ] }
}

Answer №1

When defining DataDto, you are specifying that it contains a property named data which should be of type AssetsArrayDto. However, in your JavaScript code, you are attempting to access the assets property from an instance of DataDto. Since DataDto does not have an assets property, Typescript is warning you about this inconsistency.

@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'))
@UsePipes(new ValidationPipe({ transform: true }))
@Put(':id')
async uploadAssets(
   @Request() req,
   @Param('id') campaignId: string,
   @Body() data: DataDto) {
   try {
     console.log("Data Check");
     console.log(data);

     // To correctly access the assets property, use data.data instead of data
     const { assets } = data.data;   
     console.log(data.assets[0].asset_name);
     console.log(JSON.stringify(data, null, 2));

     const a = JSON.parse(JSON.stringify(data));

     console.log(a)
     console.log(assets)

     return {
       statusCode: HttpStatus.OK,
       message: data,
     };

   } catch (error) {
     Logger.log('Validation Error: ');
     Logger.log(error);
     throw new BadRequestException(error);
   }
 }

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

Do not activate hover on the children of parents using triggers

Check out my demonstration here: http://jsfiddle.net/x01heLm2/ I am trying to achieve two goals with this code. Goal number one is to have the mini thumbnail still appear when hovering over the .box element. However, I do not want the hover event to be tr ...

Is there a way to substitute certain values retrieved from a database within sails?

I am currently working on replacing fields in the data retrieved from a database using sails. async.waterfall( [ function getscores(callback) { Score.find({course : courseId}).paginate({page : 1 , limit: 10}).populate('course') ...

Detecting if a value is less than zero

I wrote a bank script that verifies if the user's deposit amount is a positive integer. If it's not, I want to reject the transaction. Check out my code snippet below: <section id="pigBox"> <img src="images/pig.png" /> & ...

AngularJS: techniques to compel the loading of fresh code

Within my AngularJS application, I am utilizing gulp revving to automatically update the version of all JavaScript and CSS files. However, each time I push a new version of my code to production, some clients experience a mix of old and new data when loadi ...

What could be causing the alt tag to not appear in the overlay when an image is clicked?

I am struggling with an issue where the alt text for the image should be added dynamically using JavaScript and displayed beneath the image in an Overlay. However, when I click on an image, it appears in the Overlay but the alt text is not showing up. Any ...

The process of fetching an item from an array in MongoDB

After accepting or canceling a friend request, I am unable to pull it from the array. It seems that when I try to do so, nothing happens. The query matches for 1 document but no documents are actually modified. I noticed that removing the requested_at fi ...

Leveraging random attributes in Next.js without encountering the "server/client mismatch" issue

Is there a way to generate unique IDs for form inputs dynamically, in order to avoid conflicts with other elements that share the same ID? If multiple login forms are present on a single page, each with an 'email' field, setting the id property b ...

Is there a way to restrict an array to only accept distinct string literals?

export interface IGUser { biography: string; id: string; ig_id: string; followers_count: number; follows_count: number; media_count: number; name: string; profile_picture_url: string; shopping_product_tag_eligibility: boolean; username: ...

Analyzing cookie data and utilizing jQuery for data presentation

Let's brainstorm. I'm currently working on a chat bar and have successfully implemented its functionality. However, I am facing a challenge in maintaining the continuity of the chat boxes while navigating through different pages on the website. ...

Using conditional statements with a series of deferred actions in jQuery

In the scenario where I have chained the $.Deferred as shown below: $.each(data, function(k, v) { promise.then(function() { return $.post(...); }).then(function(data) { if(data)... // here is the conditions return $.post(.. ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

What is the best way to change a date from the format DD/MM/YYYY to YYYY-MM-DD

Is there a way to use regular expressions (regex) to convert a date string from DD/MM/YYYY format to YYYY-MM-DD format? ...

Combining meshes results in a lower frame rate

I have combined approximately 2500 meshes, each with its own color set, but my FPS is lower than if I had not merged them. Based on THIS article, merging is recommended to improve FPS performance. Is there something I am overlooking? var materials = new ...

Tips for returning the slider to its default position when a tab is deselected

A fantastic code snippet can be found at this link for creating an animated navigation bar. The only thing left on my wishlist is for the slider to reset to its original position if a tab is not selected. Currently, it remains static regardless of selectio ...

Converting a JSON array into a table using AngularJS

Here is the structure of my JSON data: [{"Name":["A","B","C","D","E","F"], "Age":["20","30","40","50","55","60"], "Gender":["M","M","F","M","Unknown","Unknown"]}] I am looking to create an AngularJS table that resembles the following format: Name Age ...

Discover the steps to incorporate an external JS file into Next.js 12

I am encountering an issue in my Next.js project when trying to import a local JS file. Here is the code snippet I am using: <Script type="text/javascript" src="/js.js"></Script> Unfortunately, this approach results in the ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Improving Performance: Addressing Charset Definition Issue in NextJS Lighthouse Best Practices

Encountering an error on my blog page that states: Properly define charset Error! A character encoding declaration is required. It can be achieved with a tag in the first 1024 bytes of the HTML or in the Content-Type HTTP response header. Find out more a ...

Arrange two divs with a full width of 100% next to each other

Is there a way to create two divs, each taking up 100% of the page width and side by side within a wrapper with overflow:hidden? How can I achieve this? I attempted using inline-block, but it didn't produce the desired outcome. Similarly, when I tri ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...