Here's my data, consisting of a books collection, with a books.reviews sub-collection.
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 for users to be able to submit reviews via a form, sending the review and the isbn of the book to the server, with the following conditions:
- If the book doesn't exist already with a specific isbn, add it, then add the review (it obviously doesn't already exist).
- If the book does exist...
- If the review doesn't exist for this book for this user, add it.
- If the review does exist for this book for this user, update it.
I can do this with 4 separate queries, but I know that's not optimal. What are the fewest number of queries I could use (and of course, what are those queries)?