The response body contains the right number of objects in the array, however, they are all blank

I recently embarked on a Ts.ED project utilizing TypeORM and Swagger to interact with my database. I've set up a UserController.ts file and a UserService.ts file. Within the service file, there's an async function that retrieves all users from my database.

async find(): Promise<Users[]> {
  const users = await this.connection.manager.find(Users);
  return users
}

In my controller file, I invoke the service function, find, so its response appears on swagger ui.

@Get('/')
@Returns(200, Array).Of(Users)
async findAll(): Promise<Users[]> {
  const users = await this.usersService.find()
  console.log('user',users)
  return users
}

Interestingly, while the console.log call shows everything properly, the response body in swagger ui only displays

[
  {},
  {},
  {}...
]

It presents the correct number of objects but they are empty.

However, if I modify the controller function to

@Get('/')
//@Returns(200, Array).Of(Users)
async findAll(): Promise<Users> {
  const users = await this.usersService.find()
  console.log('user',users)
  return users[0]
}

the object is displayed accurately in swagger ui, including all properties.

Any thoughts on why the array's objects appear empty?

Answer №1

Did you define the Users model correctly using the @Property decorator? Check out this link for more information.

Answer №2

If you are working with typescript and utilizing nestJs or swagger within your controllers, this code snippet can come in handy:

@Post()
@ApiBody({ type: [objectItem] })
async create(@Body() body: objectItem[]) {

Answer №3

After some investigation, I finally discovered the issue at hand. It turns out that I had misunderstood a crucial aspect of both TypeORM's and Ts.Ed's documentation. In TypeORM, the database models are referred to as Entities, which led to my confusion. I had created both a User.entity.ts and a User.model.ts file, only to realize they were mostly redundant. However, thanks to @some-user's response, I learned that adding the @Property decorator in the model file was the missing piece. Once I moved this decorator to the entity file, the previously empty objects in the array began displaying the properties correctly.

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

My default value is being disregarded by the Angular FormGroup

I am facing an issue with my FormGroup in my form where it is not recognizing the standard values coming from my web api. It sets all the values to null unless I manually type something into the input field. This means that if I try to update a user, it en ...

Optimal approach for verifying the POST request payload

My RESTful API has a POST endpoint for user creation, and I am looking to implement data validation before inserting it into the database. There are two approaches I'm considering: Approach 1: Incorporating model validation in the controller and repe ...

Securing user data after authentication: Best practices for authorizing access

Currently, I am delving into the world of authorization and authentication for my Node.js / Express.js application. In this particular case, my goal is to verify and recognize a user, followed by retrieving data from my database that corresponds with said ...

Unit test in Jest fails for an unexpected reason

I have written a method that returns a Boolean value. While the method works correctly outside of unit tests, it fails when running unit tests. Here is the code for the method: const isRushHour = (date: string): boolean => { let isRushHour: boolean = ...

Having difficulties loading my stylus stylesheet onto my jade HTML page using expressjs

Within my express application, I am attempting to load the style properties from a styles module engine. Unfortunately, I am facing difficulties in loading my style. Here is the structure of my folders: myNodeApp -node_modules -styles - ...

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Error Handling with VueJs, ExpressJs and Mongoose: Dealing with API 404

Hi there, I'm facing a 404 error when my app tries to connect to my API. My API works perfectly fine when accessed directly at 'http://localhost:3000/api/users', displaying all the data as expected. However, when I try to access the data t ...

Passport offering Residences/Assistants for Locals

After successfully replacing the everyauth/ mongoose-auth login system with a passport implementation, I am now utilizing the passport-local module for local username/password logins. While exploring some examples, I noticed that Passport automatically as ...

Creating a JSON formatted post request with Angular 4 and Rails 5

Currently, I am in the process of developing an Angular application with a Rails backend. However, I seem to be encountering some difficulties when it comes to formatting the parameters hash to meet Rails' requirements. The data involves a many-to-man ...

Selecting logic depending on the request body in NestJS

Currently, my controller looks like the following: @Controller("workflow") export class TaskWorkflowController { public constructor( private readonly jobApplicationActivityWorkflow: JobApplicationActivityService ) {} @Post("/:job- ...

Access the events on your Google calendar

I am trying to retrieve events from a public Google calendar without using OAuth authentication, but I am not receiving any response: const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Encountering ENOENT whenever I try to include a function within an express.js server

I'm currently working on creating a wrapper for the tesseract.js API to enable its use with a simple GET request in Google Apps Script, but I've encountered some difficulties. Interestingly, everything seems to be functioning perfectly until I at ...

Is it possible to use Node.js to retrieve a CSV file from a URL?

I am currently seeking a method to request a csv file from any URL in order to save it. I would prefer to achieve this using only the fs, http, request, and express modules. During testing, I attempted the following: request('http://localhost:3000/da ...

How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on ...

How to specify in TypeScript that if one key is present, another key must also be present, without redundantly reproducing the entire structure

In my code, I have a custom type defined like this (but it's not working): type MyType = | { foo: string; } | { foo: string; barPre: string; barPost: string; } | { foo: string; quxPre: string; qu ...

constructor parameters not being flagged as unused by no-unused-vars plugin

I have a variable in the constructor that is not being used, and only tsc seems to pick up on it. Even though I have tried various plugins and recommendations to get eslint to recognize the unused variable, it still doesn't work. I have experimented ...

Ensure that the output of a function aligns with the specified data type defined in its input parameters

In the code snippet provided below, there is an attempt to strictly enforce return types based on the returnType property of the action argument. The goal is to ensure that the return type matches the specific returnType for each individual action, rathe ...

What are the steps to executing commands with child processes in Node.js?

I have successfully established communication between the client and server using socket.io. I am now utilizing WebSockets to send commands from the client to the server, and I would like to execute these received commands on the server. Here is my approa ...