A guide on incorporating "this" keyword within a Mongoose UserSchema method using TypeScript

Currently, I am working on setting up a login API using Mongoose with TypeScript and JSON Web Token. As I am still new to TypeScript, I am facing an issue in the user.model file where I am unable to access any schema property using the "this" method. For example, when I try to access user.methods, it gives me a compile error stating "Property 'tokens' does not exist on type 'Document'.ts(2339)".

export interface IUser extends Document {
    name: string;
    email: string;
    password: string;
    tokens: { token: string }[];
    encryptPassword(password: string): Promise<string>;
    validatePassword(password: string): Promise<boolean>;
}
const userSchema = new Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true,
        minlength: 5,
        trim: true
    },
    tokens: [{
        token: {
            type: String,
            required: true
        }
    }]
})
userSchema.methods.generateAuthToken = async function () {
    const user = this;
    const token = jwt.sign({ _id: user._id.toString() }, "thisismysecretkey");
    user.tokens = this.tokens.concat({ token });
}

While working in the userSchema.generateAuthToken section, I am encountering the error "Property 'tokens' does not exist on type 'Document'" when attempting to use user.tokens or this.tokens. If you have any insights on what I might be doing wrong, I would greatly appreciate it. Thank you in advance.

Answer №1

Make sure to provide a specific this parameter. To learn more, refer to this parameters

import { Schema, Document } from 'mongoose';

export interface IUser extends Document {
  name: string;
  email: string;
  password: string;
  tokens: { token: string }[];
  encryptPassword(password: string): Promise<string>;
  validatePassword(password: String): Promise<boolean>;
}
const userSchema = new Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    trim: true,
  },
  tokens: [
    {
      token: {
        type: String,
        required: true,
      },
    },
  ],
});
userSchema.methods.generateAuthToken = async function (this: IUser) {
  const user = this;
  const token = user._id.toString() + 'thisismysecretkey';
  user.tokens = this.tokens.concat({ token });
};

Current package versions:

"mongoose": "^5.11.9",
"typescript": "^3.7.2"

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

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

Display the default text using ngx-translate if a key is not found or while the translation file is loading

Currently in the process of setting up a brand new Angular 7 application. I am interested in establishing a default text for translation purposes. Specifically, when utilizing the translation {{ 'wait' | translate }}, I would like to ensure that ...

What prevents us from returning Observable.of(false) in the catch block within the canActivate function?

In order to protect certain routes (admin), I utilize the canActivate feature. In this scenario, I employ an authGuard class/function: The issue arises when attempting to return an observable of boolean using: return Observable.of(false);. This approach d ...

Functionality for communicating components is only operational on a single platform

I am looking to create a service that can notify my components when there are any changes to the 'idCustomer' property. These changes should trigger certain actions in different components. Currently, I am using console.log to check if the change ...

Having difficulty carrying out tasks using the Mongoose result

Product .findAll() .then((products) => { /* Perform operations */ } An array of products is returned by the query above. For example: [ { name: Mobile, price: 10000 }, { name: Laptop ...

What is the best way to sort through my collection based on the information found in an array?

I am managing a product collection. Below is an example document from my collection: { "_id" : ObjectId("5ac0b89d08e21c226cc2992c"), "name" : "Lenovo Ideapad Yoga 510 (80S9002QIH) Laptop (AMD Dual Core A9/ 4GB/ 1TB/ Win10 Home)", "brand" : "L ...

Unexpected behavior observed with Angular Toggle Button functionality

Having trouble implementing toggle functionality in Angular where different text is displayed when a button is toggled. I keep getting an error in my code, can anyone assist? See the code below: HTML <tr> <td>Otto</td> <td> ...

Beginner's guide to using Express: a step-by-step tutorial on making API requests from client-side JavaScript to

Currently, I am immersed in a Javascript project where I utilize the Nasa Mars Rover API and Immutable Js to creatively display images and information on my webpage. By harnessing the power of pure functions and functional programming, I maintain app state ...

Utilize express.static to showcase and fetch HTML content before serving JavaScript files

I'm having trouble getting my home.html file to display properly on the browser when I'm using express.static. Here is how my directory and file layout are structured: dir main -server.js dir subMain dir routing -routes.js ...

Postman encounters failure while requesting JWT token

I've been struggling to access the view of my DRF API while testing it with Postman. Even after generating a token, I can't seem to get the request with the token right. https://i.sstatic.net/qgooX.png Every time I make the request, I keep gett ...

There seems to be an issue with receiving data through Express.js's req

Currently, I am in the process of learning how to use Node and Express in order to develop an API for an upcoming Angular application that I will be working on. However, I have encountered an issue where the req.body appears to be empty whenever I attempt ...

Creating a Higher Order Component with TypeScript using React's useContext API

Looking to convert this .js code snippet into Typescript. import React from 'react'; const FirebaseContext = React.createContext(null) export const withFirebase = Component => props => ( <FirebaseContext.Consumer> {fire ...

Searching by ObjectId in MongoDB using Mongoose yields no results

Having trouble finding a document by ObjectId in mongoose. The query is returning empty results, but when I run the same query in "MongoDB Compass," it does return the document. const mongoose = require("mongoose"); await CollectionModel.find({ "_id": new ...

"Enhancing Error Handling in Express with Node.js Middleware for Parsing

I've been working on developing a middleware to manage errors, but I'm struggling to send the correct format to my frontend. Below, I'll outline my various attempts in the hopes of getting some guidance on this issue. Attempt 1 app.use(fun ...

What is the best way to obtain clear HTTP request data in a component?

My service retrieves JSON data from the backend: constructor(private http: Http) { }; getUsers(): Observable<any> { return this.http.get('http://127.0.0.1:8000/app_todo2/users_list'); }; In the component, this data is processed: ng ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

"Troubleshooting installation errors when installing Node.js Express dependencies through npm

I'm diving into the world of node.js and currently following this useful tutorial After successfully completing steps 1-4, I encountered errors when running the npm install command in step 5. You can view the errors in image 1 here: https://i.sstati ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

How can TypeScript rules be incorporated into a Next.js project without compromising next/core-web-vitals?

In my current NextJS project which is in typescript, I have the following configuration in my .eslintrc.json: { "extends": "next/core-web-vitals" } Now, I want to include additional typescript rules, such as enforcing the rule of n ...

Cannot send response headers once they have already been sent to the client [NEXTJS]

Currently, I am engrossed in a personal project focused on creating a dashboard using NextJS. This project serves as an opportunity for me to delve into learning NextJS and the fundamental concepts of TypeScript. My primary challenge at the moment revolves ...