简体   繁体   中英

Checking if an item exists in firebase DB, and if it doesn't exist, adding new one

I'm trying to create a function for my billing system in VueJS and Firebase. Somehow, the else {...} portion of the code doesn't run, even though the item doesn't exist in the database.

  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')
    }

  }

I tried an alternative method with two separate reference instances but somehow it ran the code twice:

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')
      }

    })
  }

The issue is that the stockRef.orderByChild("Model").equalTo(m).once() method is asynchronous, meaning the exists = true part of your code will not execute until the method's callback is triggered.

Another conflict is that you are assigning true to the exists variable when checking for truthfulness. Remember, to compare you can use == or === operators.

You can try using the following approach:

    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')
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM