I am currently working on setting up a oneToMany, ManyToOne relation method and here is my progress so far (pseudocode provided below). I am using Typegoose which is essentially Mongoose with types. If you are unfamiliar with it, that's okay because this discussion is more about architecture. Specifically, I want to address the "createBook" method. As you can see in the code snippet, I am using nested "await" calls which can be inefficient. I could potentially use promises and end the method by calling
Promise.all(bookQuery, authorQuery)
, but I am facing challenges with error handling. What if one operation fails while the other succeeds? This inconsistency is not ideal (ideally, if one operation fails, the other should rollback any changes it made). How can I efficiently and effectively write the "createBook" method?
class Author extends Typegoose {
@prop()
fullName: string;
@prop({ ref: Book, default: [] })
books: Ref<Book>[];
}
class Book extends Typegoose {
@prop()
title: string;
@prop({ ref: Author })
author: Ref<Author>;
}
async createBook(title, authorId): Promise<Book> {
const book = await new this.bookRepository({
title,
author: ObjectId(authorId)
}).save();
await this.authorRepository.updateOne(
{ _id: authorId },
{ $push: { books: Types.ObjectId(book.id) } }
);
return book;
}