Search code examples
node.jstypescriptexpressmongoose

error TS2339: Property 'remove' does not exist on type 'Document<unknown,


I'm getting this error on my application

runtime Error :

TSError: ⨯ Unable to compile TypeScript: src/controllers/notes.ts:134:20 - error TS2339: Property 'remove' does not exist on type 'Document<unknown, {}, { createdAt: NativeDate; updatedAt: NativeDate; } & { title: string; text?: string | undefined; }> & Omit<{ createdAt: NativeDate; updatedAt: NativeDate; } & { ...; } & { ...; }, never>'.

134 await note.remove()

highlighted Error :

any Property 'remove' does not exist on type 'Document<unknown, {}, { createdAt: NativeDate; updatedAt: NativeDate; } & { title: string; text?: string | undefined; }> & Omit<{ createdAt: NativeDate; updatedAt: NativeDate; } & { ...; } & { ...; }, never>'.ts(2339)

Controllers/notes

import NoteModel from "../models/note";
import {RequestHandler} from 'express';
import createHttpErrors from "http-errors";
import mongoose from "mongoose";

export const deleteNote: RequestHandler = async (req, res, next) => {
    const noteId = req.params.noteId;

    try{

        if(!mongoose.isValidObjectId(noteId)){
            throw createHttpErrors(400, "invalid Note ID")
        }

        const note = await NoteModel.findById(noteId).exec();

        if(!note){
            throw createHttpErrors(404, "Note not found")
        }

        await note.remove();

        res.sendStatus(204)
    }
    catch(error){
       next(error)
    }
}

model/notes

import { InferSchemaType, model, Schema } from "mongoose";


const noteSchema = new Schema({
    title: { type: String, required: true},
    text: { type: String},
}, {timestamps: true})

type Note = InferSchemaType<typeof noteSchema>


export default model<Note>("Note",noteSchema)

router/notes

import express from 'express';
import * as NoteController from '../controllers/notes'
const router = express.Router()

router.delete('/:noteId', NoteController.deleteNote);

Solution

  • Guessing you are following the same tutorial.

    If you want to keep:

    if (!note) {
      throw createHttpErrors(404, "Note not found")
    }
    

    Then use

    await note.deleteOne()
    

    remove() can no longer be used (src: How do I remove documents using Node.js Mongoose?)