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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…