Here is my data, consisting of a collection of books, with a subcategory of books.reviews.
books = [{
_id: ObjectId("5558f40ad498c653748cf045"),
title: "Widget XYZ",
isbn: 1234567890,
reviews: [
{
_id: ObjectId("5558f40ad498c653748cf046"),
userId: "01234",
rating: 5,
review: "Yay, this great!"
},
{
_id: ObjectId("5558f40ad498c653748cf047"),
userId: "56789",
rating: 3,
review: "Meh, this okay."
}
]
}]
In Node.js (using Mongoose), I need users to be able to submit reviews through a form by submitting a review and isbn books to the server with the following conditions:
- If the book does not already exist with a specific isbn, add it and then add a review (it obviously does not exist yet).
- If the book exists ...
- If a review for this book does not exist for this user, add it.
- If a review exists for this book for this user, update it.
I can do this with 4 separate queries, but I know that this is not optimal. What is the minimum number of queries I could use (and, of course, what kind of queries)?