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:
models/user.ts
:
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<IUser>('User', userSchema);
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.
Here is a simple user class:
class User {
constructor(public username: string, public email: string, public hash: string) {
}
emailUsernameCheck(): boolean {
return this.email.includes(this.username);
}
}
I want to be able to make a call like this:
import User from '../models/user';
User.findOne({username: 'foo'}).emailUsernameCheck();
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.
Here is a sample square class:
class square {
constructor(public height: number, public width: number) {
}
area(): number {
return this.height * this.width;
}
}
I also want to be able to make a call like this:
import User from '../models/user';
User.findOne({username: 'foo'}).square.area();
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 models/user.ts
so I can do things like the examples above?