Home > database >  Property 'password' does not exist on type 'User | undefined'
Property 'password' does not exist on type 'User | undefined'

Time:10-17

Hey y'all I'm getting an error "Property '_doc' does not exist on type 'User & { _id: ObjectId; }" in one of my controllers document for getting a specific user. I am using Mongoose Typescript for my backend database. My original interface did not extend the Document class. After doing some research I found that I needed to extend my interface to Document class, which I did. I'm simply just trying to get my user's info back and I'm not sure how to do so.

This is my current User model(left) and controller(right) file: My current file setup

UPDATE: I made a minor update and added 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);

It fixed the aforementioned error, however, I am now faced with a new error: "Property 'password' does not exist on type 'User | undefined'." I definitely have a password property on my User model. Any quick fixes or recommendations?

This is my new file setup after fixing original bug: New File setup

CodePudding user response:

I think you might be getting that error from your object destructuring statement here:

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

Since you're using optional chaining on user?._doc, if user is undefined, the expression will resolve to undefined, and password can't be destructured from undefined. You can directly access the password using optional chaining (const password = user?._doc?.password), which would be undefined if either user or user._doc is nullish. Also, if you're not using the others object, you actually don't need to destructure it out like you might need to in other languages, you can just say const {password} = user._doc

CodePudding user response:

I fixed the bug by simply adding the following to my controller file:

export const getUser = async (req: Request, res: Response) => {
  try {
    const user = await User.findById(req.params.id);
    if (!!user) {
      const { password, ...others } = user._doc;
      res.status(200).json(others);
    }
  } catch(e) {
    res.status(500).json(e);
  }
};

basically IF the user exists, do the following...

  • Related