Mongoose TypeScript best practice interfaces

Viewed 209

I've been taking a look how to create different Mongoose schemas with TypeScript. Which has kept me wondering if I'm missing out on some information that is not in the official Mongoose documentation.

In the official Mongoose documentation they recommend everyone to setup the interface and then use it as a generic when you create the Schema. Like below:

// 1. Create an interface representing a document in MongoDB.
interface User {
  name: string;
  email: string;
  avatar?: string;
}

// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
  name: { type: String, required: true },
  email: { type: String, required: true },
  avatar: String
});

They also confirm that there is a second option

"Alternatively, your document interface can extend Mongoose's Document class. Many Mongoose TypeScript codebases use the below approach.". Shown below:

import { Document, Schema, model, connect } from 'mongoose';

interface User extends Document {
  name: string;
  email: string;
  avatar?: string;
}

"This approach works, but we recommend your document interface not extend Document. Using extends Document makes it difficult for Mongoose to infer which properties are present on query filters, lean documents, and other cases."

Now since there are "Many Mongoose TypeScript codebases" who utilize the second way. Should i consider using it still? What's the advantage/best practice?

Thanks in advance!

0 Answers
Related