我正在制作一个网页,但是当输入相同的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!");
}
});
}
如果您能告诉我哪里出错了,或者最好的解决方案,我将非常感激
最佳答案
您的代码存在一些问题:
- 您正在使用
phone/${Imei}/imei
构建路径,但您的变量名称拼写为imei
(而不是Imei
) >)。 JavaScript 中的大小写很重要,就像大多数编程语言一样,因此我建议密切注意拼写和大小写。 - 您没有在任何地方调用
validate()
,这意味着您的检查不会运行。 - 您没有从
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? - 您确实应该使用事务来确保没有人可以在代码中的读写操作之间索取 IMEI。
- 如果 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/