Creating a mongoose authentication model

I encountered an issue when attempting to integrate mongoose passport into my schema, resulting in the following error message:

export interface IUserModel extends IUser, Document { };

export let userSchema = new Schema({
    username: { type: String, required: true, unique: true }
}

firstName: { type: String, required: true },
const passportLocalMongoose = require("passport-local-mongoose");
userSchema.plugin(passportLocalMongoose);
export let User: Model<IUserModel> = model<IUserModel>("User", userSchema);

My steps included adding the following to app.ts (main file):

import { User } from "./schemas/user";
let passport = require("passport");
passport.use(new localstrategy(User.authenticate()));

However, this led to the error message:

error TS2339: Property authenticate does not exist on type Model<IUserModel>

If you have a solution to this problem, please kindly share it. Thank you.

Answer №1

Typescript is not aware of injections of additional values into other modules.

I faced a similar issue when working with Express. In order to access req: express.Request, I needed to inject state so I could utilize req.state in my middleware functions.

To achieve this, I used the following workaround:

import { State } from './index';

declare module 'express' {
    interface Request {
        state: State;
    }
}

(where State is a Typescript model):

export type State = {
    correlationId?: string;
    sessionId?: string;
    logger: Logger;
    out: any;
};

You can try something similar with Mongoose:

declare module 'mongoose' {
    interface Model {
        authenticate: Function;
    }
}

Another workaround involves saving to an :any variable and then using it, bypassing Typescript's control (although this method may not fully leverage Typescript's advantages). Here's an example:

import { User } from "./schemas/user";
let passport = require("passport");
const userThatCanDoAnything: any = User;
passport.use(new localstrategy(userThatCanDoAnything.authenticate()));

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

Implementing Role-Based Authentication in Node.js with Mongoose

Managing an application with two distinct roles, a User and a Photographer, presents unique challenges. The key differences lie in the presence of an isAdmin field in User, a Photo[ ] array in Photographer, and an order[ ] array in User. Despite these disc ...

Selecting a GoJS Node using keys

In Angular with TypeScript, what is the best way to select a node from a diagram based on its key? Currently, I am required to left-click a newly created node in order to select it, but I would like for it to be automatically selected upon creation. I ha ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Guide for integrating CryptoJS with Angular 2 and TypeScript within a WebPack build setup

Looking for advice on integrating the CryptoJS library with Angular 2 using TypeScript? Many existing resources are outdated and assume the use of SystemJS. Can someone provide straightforward instructions for incorporating CryptoJS with Angular 2 and Type ...

Updating inner elements during the insertion or update process in MongoDB using Mongoose

Imagine a scenario where there is a collection of documents and each document has a unique identifier called field_1. [ { field_1: 'abc', field_2: 0, field_3: [] } ] Now, let's say I want to add another documen ...

Exploring Angular 12: utilizing rxjs observables with chained subscriptions for enhanced functionality and robust error handling

Can someone help me with creating a function that I can subscribe to, returning: an observable containing the result if all operations were successful an observable with an empty string in all other scenarios foo(): void { this.uploadImage.subscr ...

The current state of this scenario is not clearly defined within the parent class

Here is the scenario that caught my attention: abstract class Base { public _obj = { name: 'Test' } print1() { console.log(this._obj) } print2() { console.log(this) } } class Child extends Base { print2( ...

A guide on creating mongoose static methods that are compatible with ESLint

Utilizing Mongoose ORM with MongoDB I have defined a static method in mongoose as follows: ConvoDataSchema.statics.randomItem = async function () { ... } and created a model using it const ConvoData = mongoose.model('ConvoData', ConvoDataSche ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

Connect to a particular Mongoose model query

In my invoice.js file, I have a self-contained model. Here is the code: 'use strict'; // load the necessary modules var mongoose = require('mongoose'); var auth_filter = require('../../auth/acl/lib/queryhook'); var invoice_d ...

What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this: const products = [ { product: 'prod_aaa', name: 'Starter' }, { product: 'prod_bbb&apos ...

Angular: Unable to locate route declaration in the specified path /src/app/app-routing.module.ts

Whenever I attempt to set up automatic routing for components that have been created using the command below ng generate module orders --route orders --module app.module I encounter the following error message The requested URL /src/app/app-routing.mod ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Refreshing the private route redirects the user to the login page

Currently, I am working on setting up a private route within my React app. I have integrated Redux and Redux-Toolkit (RTK) Query for handling state management and data fetching. The issue I am facing is that whenever I reload the private page, it redirects ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

Custom React component - DataGrid

Just starting out in the world of React and attempting to create a custom component with parameters. I'm curious about the correct approach for achieving this. Here's my current code snippet - how do I properly pass Columns, ajax, and datasourc ...

printer.printFile function is generating a blank output

Utilizing the compiler API for Typescript code generation, I encountered an issue where printer.printFile consistently outputs empty strings. Despite successfully using printer.printNode and printer.printList to print my AST, printer.printFile remains unco ...

Issue with Promise not resolving in Node when using Edge

As I explore the best way to utilize my C# dlls with Edgejs for Node, I encountered a situation where one proxy function in Node appears like this (a class method in Typescript): readSettings(args: ReadSettingsParams) : Promise<response> { let $ ...

Having trouble connecting to my MongoDB container using Node.js

I am facing an issue while trying to connect my local mongoDB docker, named "some-mongo", to my NodeJS backend server running on the same computer. The problem arises when attempting to establish the connection using the "mongoose" module. To launch my mo ...