Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs MongoDb Schema/Interface Information Duplication

I have been following the instructions for using MongoDb with Nestjs. I've got things working however it seems to me there is a rather unnecessary duplication of information (not DRY). Specifically it seems that we are required to make Db schema and also interfaces that match the schema. In my own code this looks something like this:

import { Document, Schema } from 'mongoose';

export interface IBlogPost extends Document {
  subject: string;
  body: string;
  authorId: string;
}

export const BlogPostSchema = new Schema({
  subject: String,
  body: String,
  authorId: String,
});

The rest of my code is in this repo if you want more context. The official example code is here.

Am I doing something wrong or is this really required?

like image 348
peter554 Avatar asked Mar 05 '23 12:03

peter554


1 Answers

You can check out the nest.js typegoose library. The library creates the schema definition from an annotated typescript class.

export class Cat extends Typegoose {
  @prop({ required: true })
  name: string;
}

Alternatively you can use typeorm with mongodb, which only needs one annotated typescript interface as well.

like image 119
Kim Kern Avatar answered Mar 08 '23 22:03

Kim Kern