The field 'password' is not found in the data type 'User | undefined'

Howdy everyone, I've encountered an issue stating "Property '_doc' does not exist on type 'User & { _id: ObjectId; }'" in one of my controller documents while trying to fetch a particular user. My backend database is implemented using Mongoose + Typescript. Initially, my interface did not extend the Document class. Following some research, I discovered that extending my interface to the Document class was necessary. However, I'm stuck on retrieving my user's information.

Here are my current User model (left) and controller (right) files: https://i.sstatic.net/9co2j.jpg

UPDATE: I made a small modification by adding the following to my model file:

import mongoose, { Schema, model } from 'mongoose';

export interface UserResult<T> extends mongoose.Document {
  _doc: T;
}

export interface User extends UserResult<User> {
  username: string;
  email: string;
  password: string;
};

const UserSchema = new Schema<User>({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

export default model<User>('User', UserSchema);

This adjustment resolved the previous error, but now I'm encountering a new one: "Property 'password' does not exist on type 'User | undefined'". The password property definitely exists in my User model. Any suggestions for quick fixes?

Below is the updated setup after addressing the initial bug: https://i.sstatic.net/qiqY0.jpg

Answer №1

It appears that the error you're encountering is related to the object destructuring syntax in this section of your code:

const {password, ...others} = user?._doc

If the optional chaining on user?._doc results in undefined, trying to destructure password from undefined will cause an error. To avoid this, you can use optional chaining directly to access the password like so:

const password = user?._doc?.password
. This way, if either user or user._doc is nullish, the result will be undefined. Additionally, if you're not utilizing the others object, there's no need to destructure it. Simply accessing the password with const {password} = user._doc would suffice.

Answer №2

To resolve the issue, I incorporated this solution into my controller file:

const fetchUser = async (req: Request, res: Response) => {
  try {
    const userData = await User.find({ _id: req.params.id });
    if (!!userData) {
      const { password, ...rest } = userData._doc;
      res.status(200).json(rest);
    }
  } catch(error) {
    res.status(500).json(error);
  }
};

In essence, when a user is found, execute the specified logic...

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

Creating a Typescript union array that utilizes a string enum for defining key names

Can we shorten this statement using string enum to restrict keys: Array<{ [enum.example1]: Example } | { [enum.example2]: Example } | ...> // or equivalent ({ [enum.example1]: Example } | { [enum.example2]: Example } | ...)[]; We can make it more c ...

Is it possible for me to incorporate a new feature into a library that operates using its unique interface?

I'm currently utilizing the angular-gridster2 library and I am looking to add two additional properties in the gridsterItem interface to hold some specific values. How can this be achieved? Despite creating an extended interface of their own, the pack ...

Strategies for managing multiple request keys that share the same value

In the process of this project, I am creating models and passing values from a POST request's body. My main objective is to properly define these models. Here is a JSON sample that I intend to post to MongoDB: { "signageId": "5cd857c4965f863b7c8 ...

Tracking User Behavior on Express Node.js

Currently, I have set up logging using express with winston and morgan for my backend API. My next step involves recording user activity - including timestamp, user information, and content accessed or modified - into a MySQL database. While searching onl ...

Is it feasible to restrict generic classes for particular functions?

Imagine creating a customized container in TypeScript. Let's consider this straightforward example: class Container<T> { val: T; constructor(t: T) { this.val = t; } } Now, let's say you want to implement a function that can gene ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

What steps should I follow to integrate the NextUI Tab component in my NextJS project?

Hi everyone, I am new to NextJS. I recently set up a basic NextJS starter project with NextUI by using the command npx create-next-app -e https://github.com/nextui-org/next-app-template. Now, I am trying to add a tab group with 3 tabs to the default page. ...

Having trouble converting a date to a string with a specific format in mongoose

When attempting to convert a date object to a string date format, I encountered a cast error: Cast to date failed for value "11/2020" at path "startdate" The start date property is defined as type Date in the schema: testSchema = new Mongoose.Schema({ ...

The POST request to write to a JSON file using fs.fileWrite is malfunctioning and unable to establish a connection with localhost

I am currently facing challenges with expressing myself effectively. My struggle lies in getting a post request to function properly. I aim to use the post request to update an item in a cart.json file, leveraging Node.js's fs.fileRead and fs.fileWrit ...

Creating reusable date logic with date-fns: A guide

In my Weather App, I successfully implemented code to display the date. However, I'm now contemplating the idea of writing reusable code. Is there a way for me to combine "const date and day" and use them separately? import { Weather } from "./ty ...

Reactjs and Typescript - A Powerful Duo

I'm working on creating a Searchbar that will display the author ID and picture based on user input, but I'm encountering an error in my code: any Property 'toLowerCase' does not exist on type 'never' import { useEffect, us ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

Developing a JavaScript program for ATMs that can efficiently handle and dispense money in the fewest number of notes possible

When a certain amount is entered, the code should be capable of handling figures up to 20000. For instance, if the input amount is 2600 with a card balance of 3000, the output will be as follows: New Balance - 400 Notes: 2000 * 1 500 * 1 100 * 1 Only thre ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

Webpack-hot-middleware increases the number of event listeners exponentially

When configuring my new development environment (node server + client with vanilla js), I encountered an issue with webpack-hot-middleware for live reloading front-end changes. The problem arose when using code like: $button.addEventListener('click&a ...

Javascript SQL query not returning the expected multiple rows, only returning one instead

I have a table containing multiple rows of test results, each row includes the ID of the test taker. Using the logged-in user information, I've added additional rows to the table to ensure accuracy. However, when printing the result to the console, on ...

Terminate a remotely shared ngrok session that is forwarding a React application

My coworkers and I share an ngrok account while developing a React application using 'npx create-react-app' on UNIX-like systems. Occasionally, when trying to spin up an HTTP tunnel, I encounter the message: Your account '*****@*********.com ...

error: attempting to access an undefined variable named 'access_token'

Auth0 is causing issues for me as I try to obtain the AccessToken. I encountered a difficult problem. Can someone provide a solution to this issue? The error message I received is as follows: E:\sample projects\Building-API\movieanalyst-web ...

A guide to setting properties using a Proxy object

Within my class, I have included a Proxy which is structured as follows: export class Row<T extends ModelItems> { private _row: T = <T>{} public constructor(rowItems?: T) { if (rowItems) { this._row = rowItems } return new Proxy( ...

Combining Routes in Express

I have created a basic application using node.js and express. This application features multiple routes and includes simple login/logout functionality. My goal is to ensure that all routes redirect users to a login form if they are not currently logged in. ...