Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

mongodb - 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?

question from:https://stackoverflow.com/questions/65865612/mongoose-document-type-declaration

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your MyModel has some sort of document type which extends the mongoose Document type and adds 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 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...