Search code examples
mongodbtypescriptmongoosevisual-studio-codeintellisense

Mongoose document type declaration


I know maybe this is far too basic but I can't recall how to do this properly. I want to declare a Mongoose document to use VS Code IntelliSense for retrieve data.

Right now, document is declared as any since findById() returns any:

const document = await MyModel.findById(docId);

So, whenever I want to call to something like document.updateOne() I don't have intelliSense on.

I have tried using something like:

import { Model, Document } from 'mongoose';
...
const document: Model<Document> = await MyModel.findById(docId);

But this don't give me the ability to refer internal attributes directly like document.title or any other.

So, what is the proper way to declare document?


Solution

  • Your MyModel has some sort of document type that extends the Mongoose Document type and likely adds some properties of its own. That's the generic that you want to use.

    Instead of setting the generic (<Document>) when you retrieve the document, you want to set the generic on the MyModel object itself so that the Typescript will infer the correct type for findById and for any other methods. So you want to handle this at the place where you create MyModel.

    interface MyDocument extends Document {
        title: string;
    }
    
    const MyModel = mongoose.model<MyDocument>(name, schema);
    

    Now the document is inferred to be type MyDocument | null here:

    const document = await MyModel.findById(docId);