The type error in my nestjs application is caused by my attempt to access the property _id on the result of a promise, which does not exist on the type

Within my current project, I am encountering a type error when attempting to call _id on the user object. This issue arises because mongoose automatically defines the _id, meaning it is not present in my schema where the promise is defined.

Upon changing the promise type to Promise<any>, the type error disappears.

async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

I am uncertain if this is the correct approach or if there is an alternative solution that should be implemented instead. I would prefer not to add _id to the schema to resolve this issue.

 @Prop({ auto: true})
 _id!: mongoose.Types.ObjectId;

user.schema.ts

// list of imports...

export type UserDocument = User & Document;

@Schema({ timestamps: true })
export class User {

  @Prop({ required: true, unique: true, lowercase: true })
  email: string;

  @Prop()
  password: string;

}

export const UserSchema = SchemaFactory.createForClass(User);   

users.controller.ts

@Controller('users')
@TransformUserResponse(UserResponseDto)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto) {
      const user = await this.usersService.create(createUserDto);
      return user._id;
  }

}

users.service.ts

// list of imports....  
   
@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }
}

Answer №1

Ensure that your create service method always returns a Promise<UserDocument> instead of a Promise<User>. The UserDocument type includes the _id property.

async create(createUserDto: CreateUserDto): Promise<UserDocument> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

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

Notification of Leaf Name in d3.js

I am trying to display the leaf name when it is clicked, but I am unsure how to do it. I am new to D3 and would appreciate any guidance on how to achieve this. Source: http://bl.ocks.org/mbostock/7607535 var circle = svg.selectAll("circle") .data(nod ...

Components in Angular modules that are loaded lazily with identical names

I have developed an Angular application with multiple lazy-loaded modules. Each of these modules contains different components that are conceptually similar but vary in content. For example, each module may have its own "home" component. Is it advisable t ...

Utilize paperclip and angularjs to easily upload files

I am currently working on integrating Angularjs upload functionality into my rails application: Angular File upload Below is my controller code for managing photos: def create @photo = current_user.photos.new(photo_params) respond_to do |format| if @ ...

Using React.js to select and change the color of an element

I'm developing a movie theater app, in which I am building a feature to select seats in the cinema hall and add them to the cart. Here is the function that displays the cinema hall: export default function CinemaHall(props) { const row = props.row ...

Define URL parameters within the ngResource framework

My current setup involves utilizing ngResource in my service to retrieve comments for specific news posts within my web application. However, I am facing an issue where the query for comments for a particular news post, article.comments = commentService.q ...

Tips for adjusting a duplicated row without altering the initial row

I've got a table row set up like this: <tr class="tr_clone"> <td> @part.PartIDLink </td> <td> @Html.DisplayFor(x => x.Parts[i].MFGNumber) @Html.HiddenFor(x => x.Part ...

"Help! Despite my efforts, AngularJS is still not displaying the data from

Currently diving into Angularjs and encountering a slight roadblock in fetching data from a PHP file. <head> <script> var application = angular.module("new",[]); application.controller("control",function($scope,$http){ $http.ge ...

Can JavaScript be accessed from a background thread in a Cordova Android plugin?

In my Cordova application, I am utilizing a native plugin on Android (with plans for other platforms in the future). The plugin is loaded when the application starts (<param name="onload" value="true" /> in plugin.xml) and the native code performs t ...

Vue Js: Creating an array of checkboxes

I have a collection of checkboxes sourced from the main system object where I store all system settings (referred to as getSystem{}). Within this form, I am retrieving information about a User, who possesses an array of roles []. How can I cross-reference ...

Creating a Django-powered Ajax auto page loader

I am working on a website that would greatly benefit from having an autopager feature. An autopager automatically loads the next page when scrolling to the bottom, similar to how the Reddit Enhancement Suite functions. However, implementing this in Django ...

Utilizing Smoke.js within a PHP environment

I created a PHP function to validate HTML form fields. When an error occurs, the code below will display an error message using JavaScript "alert": echo '<script type= "text/javascript">alert("account not found in database")</script>&apo ...

You do not have permission to run that command on the admin database in MongoDB Atlas

I am encountering an issue in my MongoDB Atlas cluster where I am attempting to copy a database within the same instance. However, every time I try to execute db.copyDatabase() or the copydb admin command, it results in the following error: not authorized ...

Ensuring Accessibility in Vue using Jest-Axe: It is important for buttons to have clear and distinguishable text. Is there a way to include a button name or aria-label when the content is passed through a slot

I have been focusing on enhancing the accessibility of my project by incorporating ESLint rules from vuejs-accessibility and integrating Jest-Axe. During the accessibility tests for my button components, Jest-Axe highlighted that Buttons must have discern ...

The functionality of Bootstrap tabs is compromised when used within a modal dialog

I am encountering an issue while using Django and Bootstrap to implement nav-tabs within a modal that is displayed upon clicking a button. The problem lies in the fact that when a tab is clicked, its content does not appear. Below is a basic example: {% ...

Assign custom keys to request object parameters before reaching the controller in the map

I have a Loopback 4 application where the request object's property keys are in snake_case and they correspond to our database column names which are in StudlyCase. What I want is to change the application property names to camelCase. This means that ...

What is the reason for the svg animateTransform only being triggered on the initial item?

When hovering over the first item, the animations for the others would also trigger. However, when hovering over the second item, the other items wouldn't work. How can I ensure that each item's animation triggers one by one? body { displa ...

Quote the first field when parsing a CSV

Attempting to utilize Papaparse with a large CSV file that is tab delimited The code snippet appears as follows: const fs = require('fs'); const papa = require('papaparse'); const csvFile = fs.createReadStream('mylargefile.csv&apo ...

Steps for displaying a loader after refreshing data using queryClient.invalidateQueries:1. Utilize the query

I am currently working on a project where I need to redirect to a specific page after updating an item. While the code is functioning correctly, I have encountered an issue with the loader not displaying. export const useUpdateStatusArchiveSurvey = () => ...

Sending Node.js variables to HTML with the help of Ajax

I am attempting to pass JSON results from Python to HTML using AJAX in Node.js. My objective is to collect client-side inputs, send them via AJAX to Node.js when a submit button is clicked, and then have the /data middleware execute a Python script that i ...

Utilizing a where clause within a relation table in a NestJS application with PostgreSQL database using Type

I have come across a query that looks like this async findAllEnquiries(filter: DataFilterDto): Promise<ApiResponseDto<EnquiryEntity[]>> { const take = filter.count || 10; const page = filter.pageNo > 0 ? filter.pageNo - 1 : 0; co ...