Apply a typescript class to a member of a mongoose document
<p>I have a mongoose schema in typescript and I am already using an interface for properties of the document itself. I want to create a class so when I find a document I can immediately call methods. I also want the document to contain members that are instances of other classes and call the methods those members. Is this possible? Here is what I have so far: </p>

<p><code>models/user.ts</code>:</p>

<pre><code>import mongoose from '../lib/mongoose';
const Schema = mongoose.Schema;

interface IUser extends mongoose.Document {
  username: string;
  email: string;
  hash: string;
};

var userSchema = new Schema({
    username: String,
    email: String,
    hash: String
});

export default mongoose.model&lt;IUser&gt;('User', userSchema);
</code></pre>

<p>I don't actually need to do this for my user model but it is the shortest so I thought it would be a good example. Let's say I wanted a method to check if the user's email contains their username.</p>

<p>Here is a simple user class:</p>

<pre><code>class User {
  constructor(public username: string, public email: string, public hash: string) {

  }

  emailUsernameCheck(): boolean {
    return this.email.includes(this.username);
  }
}
</code></pre>

<p>I want to be able to make a call like this: </p>

<pre><code>import User from '../models/user';
User.findOne({username: 'foo'}).emailUsernameCheck();
</code></pre>

<p>Let's also say I wanted to give each user a square with a height and width, and the square class has an area method.</p>

<p>Here is a sample square class:</p>

<pre><code>class square {
  constructor(public height: number, public width: number) {

  }

  area(): number {
    return this.height * this.width;
  }
}
</code></pre>

<p>I also want to be able to make a call like this: </p>

<pre><code>import User from '../models/user';
User.findOne({username: 'foo'}).square.area();
</code></pre>

<p>I know I can make the classes separately, give them constructors that take objects, and construct the classes that way. I will do this if it is the only way but it means importing the class separately and adds an extra step to every database lookup. It also opens up room for error since the classes are maintained separately from the schema. I would love to handle this all in my model. Is there something I can add to <code>models/user.ts</code> so I can do things like the examples above? </p>