I'm writing a NestJS api using MongoDB (and Mongoose) for the database. I have a parent document: "Writer", which may have subdocuments: "Book".
Here is the "Writer" document:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type WriterDocument = Writer & Document;
@Schema()
export class Writer {
@Prop({
required: [true, "Name is required and can't be empty!"],
unique: true
})
name: string;
}
export const WriterSchema = SchemaFactory.createForClass(Writer);
And the "Book" subdocument:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { Document } from 'mongoose';
import { Writer } from 'src/writer/schemas/writer.schema';
export type BookDocument = Book & Document;
@Schema()
export class Book {
@Prop({
required: true,
type: mongoose.Schema.Types.ObjectId,
ref: Writer.name
})
writer: Writer;
@Prop({ required: true })
name: string;
}
export const BookSchema = SchemaFactory.createForClass(Book);
I want to ensure the writer exists before inserting any book for him in the database, but if I'm right, by default, the existence of the writer is not checked, and a book can be inserted at any time without having a real writer.
I just started using NestJS and MongoDB (with Mongoose), and I don't really know how to do it. Maybe this is the way to do with these technologies but I would rather prevent this from happening.
How can I do that? With Middleware? Guard? Pipe? Something else?
Thanks in advance.