Trying to understand models in a nestjs/mongoose app

心已入冬 提交于 2019-12-24 22:25:14

问题


I am a newbie to nestjs. I have now been playing with a very simple mongodb/mongoose db with books, authors and genres. I started to have a blurry image of what models I actually need for, let's say, books.

Currently I have 2 models:

book.ts

export interface Book extends Document {
  id?: string;
  name: string;
  year?: string;
  authorId: string;
  genreId: string;
}
  • needed to inject into a service constructor @InjectModel('Book') private readonly bookModel: Model<Book> and to call book.save()

CreateBookDto.ts

export class CreateBookDto {
  @IsString()
  @IsNotEmpty()
  readonly name: string;

  @IsOptional()
  @IsNumberString()
  @Min(1000)
  @Max(3000)
  readonly year: string;

  @IsMongoId()
  readonly authorId: string;

  @IsMongoId()
  readonly genreId: string;
}
  • as I understand - needed to validate the object during creation

(plus, of course, a mongoose Schema in yet another file)

Now I bumped into a problem trying to serialize the book response and I started to think that I probably need yet another model - a Book class, which would allow me to rename properties, exclude, expose, et al. The class could basically replace the interface, except that

export class Book extends mongoose.Document

doesn't seem to work.

Now, it smells like I am misunderstanding the design - I cannot believe 3 models would be necessary to maintain in the codebase.

Question

Can someone shed light on me please - can I get away with just one single class which would satisfy all the purposes: providing the type, validation and serialization. If so, how to make the .save() part work?


回答1:


Well first of all you got some misconceptions in MongoDBs architecture a Document is a Register in the Database is not a Model when you obtain a registry from Mongo's store you are getting a Document.

Mongoose Is a ODM which means that is a layer that manages the Persistence of Data without you having to communicate whit the database directly also giving you an API for you to work with the data in the runtime. It uses a schema based architecture and that's the part you are doing wrong you are creating a Document instead of a schema.

Second the DTO is a really good practice it makes the relation between the controller and the ODM(Mongoose) loose coupled (which helps on the growth of the system).

In orther for you to achieve what you want you gotta create a Book Schema for persisting all the information. Maybe you could see the NestJS' documentation example



来源:https://stackoverflow.com/questions/58881385/trying-to-understand-models-in-a-nestjs-mongoose-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!