Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 924
Maramal Avatar asked Oct 19 '25 11:10

Maramal


2 Answers

The new recommended way of typing documents is using HydratedDocument:


import {  HydratedDocument } from "mongoose";

interface Animal {name: string}

const animal: HydratedDocument<Animal> = AnimalModel.findOne( // ...

https://mongoosejs.com/docs/typescript.html

like image 138
Sir hennihau Avatar answered Oct 22 '25 03:10

Sir hennihau


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);
like image 26
Linda Paiste Avatar answered Oct 22 '25 03:10

Linda Paiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!