Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

classes and interfaces to write typed Models and schemas of Mongoose in Typescript using definitelytyped

how can I use classes and interfaces to write typed Models and schemas in Typescript using definitelytyped .

import mongoose = require("mongoose");

 //how can I use a class for the schema and model so I can new up
export interface IUser extends mongoose.Document {
name: String;
}

export class UserSchema{
name: String;
}




var userSchema = new mongoose.Schema({
name: String
});
export var User = mongoose.model<IUser>('user', userSchema);
like image 509
afaayerhan Avatar asked Feb 07 '15 07:02

afaayerhan


1 Answers

This is how I do this:

  1. Define TypeScript class which will define our logic.
  2. Define the interface (which I name Document): that's the type mongoose will interact with
  3. Define the model (we'll be able to find, insert, update...)

In code:

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

// 1) CLASS
export class User {
  name: string
  mail: string

  constructor(data: {
    mail: string
    name: string
  }) {
    this.mail = data.mail
    this.name = data.name
  }
  
  /* any method would be defined here*/
  foo(): string {
     return this.name.toUpperCase() // whatever
  }
}

// no necessary to export the schema (keep it private to the module)
var schema = new Schema({
  mail: { required: true, type: String },
  name: { required: false, type: String }
})
// register each method at schema
schema.method('foo', User.prototype.foo)

// 2) Document
export interface UserDocument extends User, Document { }

// 3) MODEL
export const Users = model<UserDocument>('User', schema)

How would I use this? let's imagine that code is stored in user.ts, now you'd be able to do the following:

import { User, UserDocument, Users } from 'user'

let myUser = new User({ name: 'a', mail: '[email protected]' })
Users.create(myUser, (err: any, doc: UserDocument) => {
   if (err) { ... }
   console.log(doc._id) // id at DB
   console.log(doc.name) // a
   doc.foo() // works :)
})
like image 52
Manu Avatar answered Sep 21 '22 15:09

Manu