【问题标题】:Avoid two request at same time in firestore在 Firestore 中同时避免两个请求
【发布时间】:2019-06-01 16:46:42
【问题描述】:

我创建了一个函数来与 firestore 数据库进行通信。 首先,检查关系中是否存在某些东西。如果没有,那么添加一些东西。 如果某些东西已经存在,则使用数据,然后删除查询关系中的条目。但是您必须在函数中添加它(其他部分)。现在问题出现了,当两个用户同时执行该功能时会发生什么。 有没有办法在第一个用户完成请求时将第二个用户放入队列中?

let ref = db.collection('relation1').doc('test').collection('user');
      var checkForAdd = ref.get().then(snapshot => {
        if(snapshot.size < 1){
            db.collection('relation1').doc('test').collection('user').add({
                user: 'Test',
                createdAt: Date.now()
            }).catch(err =>{
                console.log(err)
            })
        }

【问题讨论】:

标签: javascript database firebase transactions google-cloud-firestore


【解决方案1】:

Cloud Firestore 支持读取和写入数据的原子操作。在一组原子操作中,要么所有操作都成功,要么一个都不应用。

https://firebase.google.com/docs/firestore/manage-data/transactions

// Create a reference to the user doc you want to create if it doesn't exist.
const userCollectionRef = db.collection('relation1').doc('test').collection('user');
const userDocRef = userCollectionRef.doc('documentID');

return db.runTransaction(transaction => {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(userDocRef).then(userDoc => {
        if (userDoc.exists) {
            // If something already exists then use the data and
            // then delete the entry in the queried relation.
        } else {
            transaction.update(userDocRef, {
                user: 'Test',
                createdAt: Date.now()
            });
        }
    });
}).then(() => {
    console.log("Transaction successfully committed!");
}).catch(error => {
    console.log("Transaction failed: ", error);
});

【讨论】:

  • 感谢您的帮助!但是你能告诉我为什么 userDoc.exists 总是假的,即使里面有东西吗?
  • 我将文档留空,因为在这种情况下我想更喜欢 autoid(doc())
  • 自动 ID 本身应该是唯一的,因此文档不应该存在
  • 是否有可能检查整个集合是否为空?也许通过检查大小或其他什么?
  • 解释一下你正在做的事情的上下文,你是否将子路径硬编码到你的userCollectionRef 中,或者是否有任何动态值? “用户”集合,您希望其中一次有多少个文档?
猜你喜欢
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2013-01-21
  • 2018-03-31
  • 2017-10-31
  • 1970-01-01
相关资源
最近更新 更多