How to ensure that multiple documents are saved?

Viewed 20

I'm trying to implement many-to-many relationship. The code below works just fine, but I'm worried that under some circumstances it might fail. For example, if the server is overloaded and one save operation fails — it would leave me with only one document in the database. One solution to this would be to use transactions. Transaction lets execute multiple operations in isolation and potentially undo all the operations if one of them fails. In the docs I stumbled upon this line:

MongoDB currently only supports transactions on replica sets, not standalone servers

From what I understand I use a standalone server and therefore I can't use transactions. What are my options? Any advice?

  const AuthorSchema = new mongoose.Schema({
    name: String,
    books: [{ type : mongoose.Types.ObjectId, ref: 'Book' }]
  })
  const BookSchema = new mongoose.Schema({
    title: String,
    authors: [{ type : mongoose.Types.ObjectId, ref: 'Author' }]
  })
  const Author = mongoose.model('Author', AuthorSchema)
  const Book = mongoose.model('Book', BookSchema)

  const author = new Author({ name: 'Batman' })
  const book = new Book({ title: 'How to cook a bat and not cause a pandemic' })

  author.books.push(book._id)
  book.authors.push(author._id)

  await author.save()
  await book.save()
0 Answers
Related