检查Firebase数据库中是否存在一项,如果不存在,则添加新项

时间:2018-07-23 11:09:44

标签: javascript firebase firebase-realtime-database

我正在尝试在VueJS和Firebase中为我的计费系统创建一个功能。 不知何故,即使该项目在数据库中不存在,代码的其他{...}部分也不会运行。

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

    })
  }

1 个答案:

答案 0 :(得分:4)

问题在于MvxAndroidActivityLifetimeListener方法是异步的,这意味着代码的public class MvxAndroidLifeTimeMonitor : IMvxAndroidActivityLifetimeListener, IMvxAndroidCurrentTopActivity { ... public void OnPause(Activity activity) { Activity = activity; MethodA(); } public void OnResume(Activity activity) { Activity = activity; MethodB(); } ... } 部分在触发该方法的回调之前不会执行。

另一个冲突是,您在检查真实性时将public class Setup : MvxAndroidSetup<App> { ... protected override void InitializePlatformServices() { var lifetimeMonitor = new MvxAndroidLifeTimeMonitor(); Mvx.RegisterSingleton<IMvxAndroidActivityLifetimeListener>(lifetimeMonitor); Mvx.RegisterSingleton<IMvxAndroidCurrentTopActivity>(lifetimeMonitor); } ... } 分配给stockRef.orderByChild("Model").equalTo(m).once()变量。请记住,要进行比较,您可以使用exists = truetrue运算符。

您可以尝试使用以下方法:

exists