[英]Firebase Transactions Reservations System
我正在使用 firebase 构建预订系统。 用户可以 select 多个席位,我想将它们写在我的文档中。 选定的座位在数组内,它们是对象,如下所示:
{
reservationId: 'id',
selectedSeats: [{"x": 0, "y": 0,},
{"x": 1, "y": 0,},
{"x": 2, "y": 0,}]
}
我想确保没有其他用户可以使用至少 1 个相同的事务席位写入数据库。
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);
});
如果在文档内的每个 object 的数组中找到一个席位,我该如何使交易失败?
您可以使用array-contains-any
来检查数据库上是否已经保留了任何座位,并根据结果返回成功或失败的 promise,您还需要在交易之前创建对空文档的引用可以在其中创建文档,如下所示:
//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);
});
注意:正如您在array-contains-any
的文档中看到的那样,此 where 子句将限制为您的reservation.selectedSeats
数组上的 10 个值。 此外,我不确定您是否必须使用venueId
来获取空文档,因为您想使用该 ID,所以我鼓励您尝试两种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.