我正在寻找一种创建 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)
方法返回的查询不是 DocumentReference,这是事务接受的唯一类型。因此我的问题是,如何在 java/kotlin 中实现这样的事务?
我在 this blog post 看到过类似的东西使用管理 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);
});
});
关于android - 如何在需要找到目标文档的地方创建 firestore 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678663/