javascript - 如何避免 Firebase/Cloud Firestore 中的重复数据

标签 javascript firebase firebase-realtime-database

我正在制作一个网页,但是当输入相同的ID时应该会出现错误,但我无法做到这一点。

 function save () {
    if (validate  = true) {
        console.log("exists!")
    }else {
        
    var imei = document.getElementById('imei').value;
    var marca = document.getElementById('marca').value;
    var referencia = document.getElementById('referencia').value;
    var precio = document.getElementById('precio').value;

    db.collection("phone").add({
        Imei: imei,
        Marca: marca,
        Referencia: referencia,
        Precio: precio
    })
        .then(function (docRef) {
            document.getElementById('imei').value = '';
            document.getElementById('marca').value = '';
            document.getElementById('referencia').value = '';
            document.getElementById('precio').value = '';
        })
        .catch(function (error) {
            window.alert("Error adding document: ", error);
        });
    }
}save();

function validate () {
    firebase.database().ref(`phone/${Imei}/imei`).once("value", snapshot => 
    { const imei = snapshot.val(); 
        if (imei){ 
            console.log("user exists!"); 
        } 
    }); 
}

如果您能告诉我哪里出错了,或者最好的解决方案,我将非常感激

最佳答案

您的代码存在一些问题:

  1. 您正在使用 phone/${Imei}/imei 构建路径,但您的变量名称拼写为 imei(而不是 Imei) >)。 JavaScript 中的大小写很重要,就像大多数编程语言一样,因此我建议密切注意拼写和大小写。
  2. 您没有在任何地方调用 validate(),这意味着您的检查不会运行。
  3. 您没有从 validate() 返回任何内容。由于您想要返回的内容来自异步调用中的数据库,因此您只能使用 Promise 或 async/await 返回它。这个问题本身就有答案,所以我建议你学习Firebase, retrieving data asynchronously , How to return values from async functions using async-await from function?How to return value from an asynchronous callback function?
  4. 您确实应该使用事务来确保没有人可以在代码中的读写操作之间索取 IMEI。
  5. 如果 IMEI 值应该是唯一的,最好将其用作 key ,而不是用作属性值。在这里阅读更多相关内容:

将所有这些结合起来,更好的实现可能如下所示:

function save () {
    var imei = document.getElementById('imei').value;
    var marca = document.getElementById('marca').value;
    var referencia = document.getElementById('referencia').value;
    var precio = document.getElementById('precio').value;

    var imeiDocRef = db.collection("phone").doc(imei);

    db.runTransaction(function(transaction) {
        // This code may get re-run multiple times if there are conflicts.
        return transaction.get(imeiDocRef).then(function(imeiDoc) {
            if (imeiDoc.exists) {
                throw `IMEI '${imei}' already exist!`;
            }

            transaction.set(imeiDocRef, { 
                Imei: imei,
                Marca: marca,
                Referencia: referencia,
                Precio: precio
            });
        });
    }).then(function() {
        console.log("Transaction successfully committed!");
        document.getElementById('imei').value = '';
        document.getElementById('marca').value = '';
        document.getElementById('referencia').value = '';
        document.getElementById('precio').value = '';
    }).catch(function(error) {
        console.log("Transaction failed: ", error);
    });
}

关于javascript - 如何避免 Firebase/Cloud Firestore 中的重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60793189/

相关文章:

javascript - 如何在 javascript 中更新 firebase-messaging-sw.js

javascript - 如何在 KonvaJS 中将过滤器应用于具有图像填充的形状?

javascript - 用于加载 html 页面的 html/javascript 代码

android - 身份验证后在 Firestore 中查询 uid 文档 => IllegalStateException

java - 如何从Firebase实时数据库获取两个变量

ios - Firebase 实时数据库中的节点回调没有数据?

android - 使用 Firebase 实时数据库时如何将用户从非授权转换为授权的最佳方法

ios - 如何将 Firebase 中的用户个人列表抓取到表格 View

javascript - 根据一定条件删除ul中的最后一个元素

javascript - 选择按钮 ng 模型值在 ng 内未定义 if