I 'm trying to bind my Model with a mongoose schema using Typescript. I have my IUser interface:
export interface IUser{
_id: string;
_email: string;
}
My User class:
export class User implements IUser{
_id: string;
_email: string;
}
My RepositoryBase:
export class RepositoryBase<T extends mongoose.Document> {
private _model: mongoose.Model<mongoose.Document>;
constructor(schemaModel: mongoose.Model<mongoose.Document>) {
this._model = schemaModel;
}
create(item: T): mongoose.Promise<mongoose.model<T>> {
return this._model.create(item);
}
}
And finally my UserRepository which extends RepositoryBase and implements an IUserRepository (actually empty):
export class UserRepository extends RepositoryBase<IUser> implements IUserRepository{
constructor(){
super(mongoose.model<IUser>("User",
new mongoose.Schema({
_id: String,
_email: String,
}))
)
}
}
Thr problem is that typescript compiler keeps saying : Type 'IUser' does not satisfy the constraint 'Document'
And if I do:
export interface IUser extends mongoose.Document
That problem is solved but the compiler says: Property 'increment' is missing in type 'User'
Really, i don't want my IUser to extend mongoose.Document, because neither IUser or User should know about how Repository work nor it's implementation.
Mongoose introduced officially supported TypeScript bindings in v5. 11.0. Mongoose's index.
Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
A Schema represents an ECSchema in TypeScript. It is a collection of Entity-based classes. See the BIS overview for how ECSchemas are used to model information. ECSchemas define classes for models, elements, and aspects, as well as ECRelationships.
Mongoose is an ODM that provides a straightforward and schema-based solution to model your application data on top of MongoDB's native drivers.
I solved the issue by referencing this blog post.
The trick was to extends the Document
interface from mongoose
like so:
import { Model, Document } from 'mongoose';
interface User {
id: string;
email: string;
}
interface UserModel extends User, Document {}
Model<UserModel> // doesn't throw an error anymore
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With