检查firebase数据库中是否存在某个项目,如果该项目不存在,则添加新项目
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检查firebase数据库中是否存在某个项目,如果该项目不存在,则添加新项目相关的知识,希望对你有一定的参考价值。
我正在尝试为VueJS和Firebase中的结算系统创建一个功能。不知何故,代码的else {...}部分不会运行,即使数据库中不存在该项。
var item
for (item in this.items) {
var a = this
var s = this.items[item].Stock
var sup = this.newStockSupplier
var m = this.items[item].Model
var exists = false
stockRef.orderByChild("Model").equalTo(m).once("value",snapshot => {
if (snapshot.exists()){
exists = true
}
});
console.log(exists)
if (exists = true){
stockRef.orderByChild("Model").equalTo(this.items[item].Model).on("child_added", function(snapshot) {
console.log('Item exists in DB')
var stockItemRef = db.ref('stock/' + snapshot.key + '/Stock')
stockItemRef.transaction(function(currentStock) {
return currentStock + s
})
console.log('Updated Stock.')
})
}
else {
console.log("Item doesn't exist in DB")
var newItem = new Object()
newItem.Model = a.items[item].Model
newItem.Stock = a.items[item].Stock
newItem.Supplier = a.newStockSupplier
stockRef.push(newItem)
console.log('Added new product')
}
}
我尝试了一个带有两个独立引用实例的替代方法,但不知怎的,它运行了两次代码:
stockRef.orderByChild("Model").equalTo(this.items[item].Model).on( "child_added", function(snapshot) {
if (snapshot.val() !== null) {
var stockItemRef = db.ref('stock/' + snapshot.key + '/Stock')
stockItemRef.transaction(function(currentStock) {
return currentStock + s
})
console.log('Updated Stock.')
}
})
stockRef.orderByChild("Model").equalTo(this.items[item].Model).on("value", function(snapshot) {
if (snapshot.val() === null) {
// add code here to create new field
var newItem = new Object()
newItem.Model = this.items[item].Model
newItem.Stock = this.items[item].Stock
newItem.Supplier = this.newStockSupplier
console.log(newItem)
stockRef.push(newItem)
console.log('Added new product')
}
})
}
答案
问题是stockRef.orderByChild("Model").equalTo(m).once()
方法是异步的,这意味着在触发方法的回调之前,代码的exists = true
部分将不会执行。
另一个冲突是你在检查真实性时将true
分配给exists
变量。请记住,比较你可以使用==
或===
运算符。
您可以尝试使用以下方法:
var item
for (item in this.items) {
var a = this
var s = this.items[item].Stock
var sup = this.newStockSupplier
var m = this.items[item].Model
var exists = false
stockRef.orderByChild("Model").equalTo(m).once("value", snapshot => {
// Declare your code inside the callback function
if (snapshot.exists()) {
stockRef.orderByChild("Model").equalTo(this.items[item].Model).on("child_added", function (snapshot) {
console.log('Item exists in DB')
var stockItemRef = db.ref('stock/' + snapshot.key + '/Stock')
stockItemRef.transaction(function (currentStock) {
return currentStock + s
})
console.log('Updated Stock.')
})
} else {
console.log("Item doesn't exist in DB")
var newItem = new Object()
newItem.Model = a.items[item].Model
newItem.Stock = a.items[item].Stock
newItem.Supplier = a.newStockSupplier
stockRef.push(newItem)
console.log('Added new product')
}
});
}
以上是关于检查firebase数据库中是否存在某个项目,如果该项目不存在,则添加新项目的主要内容,如果未能解决你的问题,请参考以下文章
如何检查 Firebase Firestore 的数组中是不是存在元素?