Skip to content

Instantly share code, notes, and snippets.

@iampeterbanjo
Last active September 12, 2019 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iampeterbanjo/cd7d9ec3212717f90556cf17f8170e53 to your computer and use it in GitHub Desktop.
Save iampeterbanjo/cd7d9ec3212717f90556cf17f8170e53 to your computer and use it in GitHub Desktop.
How to model types in Typescript and Mongoose
/*
Lets have type models in Typescript and keep it simple
- borrows from https://brianflove.com/2016/10/04/typescript-declaring-mongoose-schema-model/
- validation is useful when parsing data from external APIs
- avoids typegoose, class-validator, class-transform in favour of stable features
*/
import * as mongoose from 'mongoose';
import { Document, Model, Schema, model } from "mongoose";
import jointz, { ExtractResultType } from "jointz";
const UserValidator = jointz.object({
email: jointz.string(),
firstName: jointz.string(),
lastName: jointz.string(),
})
type UserType = ExtractResultType<typeof UserValidator>;
interface UserModel extends UserType, Document {
}
const userSchema = new Schema({
createdAt: {
type: Date,
defaults: new Date()
},
email: String,
firstName: String,
lastName: String,
})
const User: Model<UserModel> = model<UserModel>('User', userSchema);
(async () => {
await mongoose.connect('mongodb://localhost:27017/ts-models', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const props: UserType = { email: 'test@me.com', firstName: 'First', lastName: 'Last' };
const user = new User(props);
await user.save();
const invalid = { fullName: 'First Last' };
if(!UserValidator.isValid(invalid)) {
console.warn('Invalid user props')
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment