我正在制作一个网页,但是当输入相同的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!");
}
});
}
如果你能告诉我哪里有错误,或者最好的解决方案,我会非常感激的。
发布于 2020-03-21 21:42:13
您的代码有几个问题:
phone/${Imei}/imei构建路径,但是变量名拼写为imei (而不是Imei)。在JavaScript中,情况很重要,就像在大多数编程语言中的情况一样,所以我建议密切注意拼写和大小写。validate(),这意味着您的检查没有运行。validate()返回任何内容。而且,由于您希望返回的内容来自异步调用中的数据库,所以只能通过承诺或async / await来返回它。因此,我建议您学习Firebase, retrieving data asynchronously、How to return values from async functions using async-await from function?和How to return values from async functions using async-await from 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);
});
}https://stackoverflow.com/questions/60793189
复制相似问题