我正在寻找一种创建 firestore 事务的方法,在该事务中我从查询中找到文档,然后在事务中修改该文档。
类似的东西(kotlin):
firestore.runTransaction { transaction ->
val snapshot = transaction.get(db.collection("document")
.whereEqualTo("someField", null)
.orderBy("creationDate", ASCENDING)
.limit(1L))
val myObject = snapshot.toObject(MyObject::class.java)
myObject.someFiled = "123"
transaction.set(snapshot.reference, myObject)
}
这里的问题是返回的查询.limit(1)
method 不是 DocumentReference,这是事务接受的唯一类型。因此我的问题是,在java/kotlin中如何实现这样的事务?
我见过类似的东西这篇博文 https://medium.com/@feloy/building-a-multi-player-board-game-with-firebase-firestore-functions-part-1-17527c5716c5使用管理 SDK:
return trs.get(db.collection('rooms')
.where('full', '==', false)
.where('size', '==', size)
.limit(1));
经过调查,您似乎无法在 Kotlin/Java 中执行此操作,它不受支持。您必须创建云函数并执行类似以下操作:
exports.executeTransaction = functions.https.onRequest(async (req, res) => {
const db = admin.firestore();
const query = db
.collection('collection')
.where('name', '==', 'name')
.limit(1);
db.runTransaction(transaction => {
return transaction
.get(query)
.then((querySnapshot) => {
const gameDocSnapshot = querySnapshot.docs[0];
const gameData = gameDocSnapshot.data();
transaction.update(gameDocSnapshot.ref, { name: 'change' });
return gameData;
})
})
.then((gameData) => {
res.send(gameData);
console.log('Transaction successfully committed!', gameData);
})
.catch((error) => {
res.send('Transaction failed:' + error);
console.log('Transaction failed:', error);
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)