Mongoose Error: Typescript String Error: 'not assignable to type 'string'

I need help with setting up a logout route in my express backend. The idea is that when a user logs out, their JWT token should be stored in a blacklist Mongo database to prevent reusing the same token for login.

The issue I'm facing is an error related to my blacklist schema:

Type '{ type: StringConstructor; required: true; }' is causing a TypeScript error as it's not compatible with type 'string'.ts(2322) (property) token: { type: StringConstructor; required: true; }

This is how my blacklist Mongo Schema looks like:

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import mongoose, { Schema } from "mongoose";
import { BlacklistMongo } from "../types/blacklist";

const blacklistSchema: Schema<BlacklistMongo> = new mongoose.Schema({
    token: {
        type: String,
        required: true
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
}, { timestamps: true });

blacklistSchema.set('toJSON', {
    transform: (_document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString();
        delete returnedObject._id;
        delete returnedObject.__v;
    }
});

export default mongoose.model<BlacklistMongo>('Blacklist', blacklistSchema);

logoutRouter:

import express from 'express';
import middleware from '../utils/middleware';
import { Response } from 'express';
import { BlacklistMongo } from '../types/blacklist';
import blacklist from '../models/blacklist';

const logoutRouter = express.Router();

logoutRouter.post('/', async (request, response, next) => {
    try {
        const token: string | null = middleware.getTokenFrom(request);
        if (!token) {
            throw new Error('Token not found');
        }

        const tokenid: Promise<string | Response> = middleware.tokenValidator(request, response);
        if (tokenid instanceof Response) {
            return tokenid;
        }

        const addedToken: BlacklistMongo = new blacklist({
            token: token
        });

        await addedToken.save();
        response.status(200).json('You have been successfully logged out!');
    } catch (exception) {
        next (exception);
    }
});

export default logoutRouter;

Answer №1

After much consideration, I made the decision to eliminate the schema and start fresh with the code, excluding users from the process. Surprisingly, this approach yielded positive results.

Structure:

import { Document } from "mongoose";

export interface BlacklistMongo extends Document {
    token: string;
}

export interface BlacklistType {
    token: string;
}

The Blacklist model:

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint-no-unsafe-call */
import mongoose, { Schema } from "mongoose";
import { BlacklistMongo } from "../types/blacklist";

const blacklistSchema: Schema<BlacklistMongo> = new mongoose.Schema({
    token: { type: String, required: true }
});

blacklistSchema.set('toJSON', {
    transform: (_document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString();
        delete returnedObject._id;
        delete returnedObject.__v;
    }
});

export default mongoose.model<BlacklistMongo>('Blacklist', blacklistSchema);

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

Making Angular Material compatible with Webpack and TypeScript

I am facing a challenge with my angular-typescript project managed by webpack. The issue arises when I attempt to integrate the angular-material library, and I am encountering significant difficulties. Currently, the html portion of my code appears as fol ...

Failed to establish WebSocket connection in Express JS to wss without any apparent error, yet successful in maintaining communication

Snippet of code demonstrating websocket connection setup using Express JS: socket.js const ip_address = `${process.env.MIX_HTTPS_APP_URL}`; const socket_port = `${process.env.MIX_EXPRESS_PORT}`; const URL = ip_address + ":" + socket_port; export ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

The login data I tried to send through postman resulted in an error message

So, I've encountered a strange error while passing user credentials through Postman. Interestingly, one tab is giving me an error while another tab is functioning correctly. I have double-checked and confirmed that everything in both tabs of Postman i ...

Implement method functionality within TypeScript interfaces

I've encountered a scenario where I have an interface that will be utilized by multiple classes: interface I { readonly id: string; process(): void; } My objective is to pass the id through a constructor like so: class A implements I {...} let a: ...

retrieve all users who are not currently in the group

I'm currently struggling to retrieve all users who are not members of a particular group within a many-to-many association. After investing several hours into researching and experimenting, I've developed the following code. However, it falls sh ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

The inclusion of a custom list preview with prepare in the sanity schema results in errors during the construction

I recently started working with next.js, TypeScript, and Sanity, and everything has been going smoothly so far. I have multiple schemas defined in my project and it works fine in development. The linting checks also do not show any errors. However, when I ...

The endpoint for the Express Get request encountered an issue and returned an error 500 with the message: "Failed to cast value

Can someone offer some assistance, please? I am attempting to seed some data to MongoDB Atlas, so I have coded an API for this purpose (thanks Basir^^): productRouter.get('/seed', expressAsyncHandler(async (req, res) => { console.log('foo ...

Guide on incorporating Firebase "onSnapshot" listener values to update a Vue "ref" variable

I have implemented a Vue composable feature that utilizes a Firebase onSnapshot listener to track data changes. The goal is to update a ref called documentsArray whenever there is a change detected by the listener. Interestingly, when I log the contents ...

Filtering database results from an Angular component

I am currently working on an Angular component and I have a result variable in the .ts file that stores data retrieved from the database. My goal is to filter this result variable to display only 20 records and sort them by date either in ascending or de ...

Modifying the State in a Class Component

private readonly maxSizeOfDownloadedFiles: number = 1000000; state = { totalSum: this.maxSizeOfDownloadedFiles }; handleCallback = () => { this.setState({ totalSum: 12 }) alert('totalSum ' + this.state.totalSum); }; Upon executing the ...

Tips for incorporating the closeAutocomplete function into ng4-geoautocomplete

Hey there! I've incorporated the ng4-autocomplete component into my custom component and now I'm trying to figure out how to detect when the autocomplete dropdown closes. Can you help me out with implementing the "closeAutocomplete" method? Let& ...

Tips on how to remove a function from a union

type A = (() => void) | (() => number) | string type B = Another<A> // string Is there a way to remove all functions from type A? This would result in type B being string ...

A TypeScript function that returns the ReturnType of a specific callback function

Is it possible to define an annotation for a function that accepts a callback, and have the function return type determined by the callback's return type? // Suppose the callback takes a number as argument function processCallback(cb: (arg:number) =&g ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

Unfortunately, node-postgres is unable to display the result set for stored procedures

Is there a way to trigger an error on the node side when using a stored procedure to create a character? The stored procedure handles validation of parameters before inserting them into the database, but when invalid data is passed through the web interfac ...

Do applications that I allocate to particular ports also function as servers?

Could the applications I assign to specific ports also be considered as servers? I have done a lot of research but have been unable to find clear answers. If they are not considered servers, are there separate servers for different ports? Any help would b ...

Error in AngularJs: Unable to assign value to 'showGreeting' property because it is null

Currently, I am utilizing yeoman angularjs-fullstack for project generation. Now, my task is to customize it according to my preferences. I have limited experience with AngularJS and TypeScript, so any feedback would be greatly appreciated, not just the so ...