【问题标题】:Data keeps on duplicating after adding to database添加到数据库后数据不断重复
【发布时间】:2017-09-14 11:28:04
【问题描述】:

我有一个起始 id 为 1 的表。我有一个函数,它使用 limitToLast(1) 获取最后添加的 id 并添加 1,以便我将添加到数据库的下一个数据将 2 作为如果最后添加的 id 是 1,则键。但是发生了什么:

它成功地将 2 添加为我添加的数据的键,但它继续添加更多并复制我的数据。 这是我的代码:

   function uploadProperty() {   

  user = firebase.auth().currentUser;
  var selectedFile;

 var propertiesref = db.ref('property/');
  propertiesref.orderByChild("property").limitToLast(1).on("child_added", 
  function(snapshot) {

   var getkey = Number(snapshot.key);
   var id = getkey + 1;
   firebase.database().ref("property/" + id).set({

     property_id: id,
     user_id: user.uid,
     property_desc: $("#desc").val() , 
     property_address: $("#address0").val() ,    
     property_slot: $("#slot").val(),
     property_price: $("#price").val(),
     rent_type: $("#renttype").val(),
     type: $("#type").val(),
     lat: $("#lat").val(),
     lon: $("#lon").val(),
     date_created: $("#datecreated").val(),  
     image_path: $("#image").val()  

  });

   desc.value = '';   
  address0.value = '';  
  slot.value  = '';
  price.value  = '';
  type.value  = '';
  renttype.value  = '';
  lat.value  = '';
  lon.value  = '';


     });
  }

【问题讨论】:

  • 感谢编辑先生:D

标签: javascript firebase web firebase-realtime-database


【解决方案1】:

您应该使用once() 而不是on()on() 让监听器保持连接状态,所以当你存储一个新的孩子时:

firebase.database().ref("property/" + id).set(...);

监听器再次触发。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多