I am building a reservation system using firebase. The user can select a number of seats and i want to write them in my document. The selected seats are inside an array and they are objects, like so:
{
reservationId: 'id',
selectedSeats: [{"x": 0, "y": 0,},
{"x": 1, "y": 0,},
{"x": 2, "y": 0,}]
}
I want to ensure that no other user could write to the database with at least 1 same seat with transactions.
let transaction = db.runTransaction(t => {
return t.get(venueId)
.then(doc => {
//I need to get all the objects inside the document and check their array of reservations.
t.set(venueId, {reservation});
});
}).then(result => {
console.log('Transaction success!');
}).catch(err => {
console.log('Transaction failure:', err);
});
How can i make the transaction fail if a seat is found in the array of each object inside the document?
You could use array-contains-any
for checking if there are any of your seats reserved on the db already and return a sucessful or failing promise depending on the results, also you need to create a reference to an empty document outside the transaction before you can create the document inside it, here is what it could look like:
//reference to a document that still does not exists
var docRef = db.collection(reservation).doc()
let transaction = db.runTransaction(t => {
return t.get(venueId)
.then(doc => {
db.collection('reservation')
.where('selectedSeats', 'array-contains-any', reservation.selectedSeats)
.get()
.then(snapshot =>{
if (snapshot.empty) {
t.set(docRef, {
uid: venueId,
reservation: reservation
});
return Promise.resolve('Reservation Complete');
}
return Promise.reject('Seats already taken');
})
});
}).then(result => {
console.log('Transaction success!');
}).catch(err => {
console.log('Transaction failure:', err);
});
NOTE : As you can see on the documentation for array-contains-any
, this where clause will be limited to 10 values on your reservation.selectedSeats
array. Also I am not sure if you have to use venueId
to get the empty document or not, since you want to use that ID, so I encourage you to try both ways.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.