Reputation: 833
I'm trying to follow the instructions given in the Mongoose documentation for their support of TypeScript: https://mongoosejs.com/docs/typescript.html.
In the docs, they provide the following example:
import { Schema, model, connect } from 'mongoose';
// 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
});
// 3. Create a Model.
const UserModel = model<User>('User', schema);
They also provide an alternative example where the interface is extending Document
:
interface User extends Document {
name: string;
email: string;
avatar?: string;
}
They recommend not to use the approach of extending the Document
. However, when I try their exact code (without extends
) I get the following errors:
Type 'User' does not satisfy the constraint 'Document<any, {}>'.
Type 'User' is missing the following properties from type 'Document<any, {}>': $getAllSubdocs, $ignore, $isDefault, $isDeleted, and 47 more.
I'm using Mongoose v 5.12.7. Is there something I don't understand about this? How can I create the schema without extending the document? I want to test it later on, and I don't want to have to mock 47 or more properties...
Upvotes: 5
Views: 3912
Reputation: 44
Removing @types/mongoose
and updating mongoose works for me. you don't need @types/mongoose
because mongoose supports typescript starting form version 5.11.0
Remove @types/mongoose with:
yarn remove @types/mongoose
Update mongoose with:
yarn update mongoose
Upvotes: 0
Reputation: 833
OK, I figured the issue. I had two problems. First, I was using the third-party @types/mongoose
package, which is no longer needed as Mongoose natively supports TypeScript.
However, the main issue was actually the version. Although in the docs it says that the new support exists since v5.11.0, the difference between v5.12.7 which I had installed and the current version—5.12.12 actually was important. Once I updated the version all the errors disappeared.
Upvotes: 2