Check firebase for an existing object based on attributes, prevent duplicates

萝らか妹 提交于 2019-12-04 17:23:03

Store an index for each entry with something like the following:

/wishes/$wishid/ (song, artist)
/wish_index/$hash/$wishid

Create $hash using a hash algorithm:

var fb = new Firebase(URL);

function saveWishEntry( song, artist ) {
  var wishRef = fb.child('wishes').push();
  wishRef.set({
     song: song, artist: artist, likes: 0
  }, function(err) {
     if( err ) throw err;
     saveWishIndex(wishRef.name(), song, artist);
  })
}

function saveWishIndex(key, song, artist) {
  // http://phpjs.org/functions/md5/
  var hash = MD5(song)+':'+MD5(artist);
  fb.child('wish_index/'+hash).set(key);
}

Now when you want to know if a record exists, simply look it up in the index:

// callback will be passed either a {string}key or null(not found)
function wishId(song, artist, callback) {
   fb.child('wish_index/'+hash).once('value', function(snap) {
       callback( snap.val() );
   });
}

If you want something to be unique, the obvious solution would be to use them as the key...

However if you want two keys, I believe you can use 'priority' as a secondary key (not automatically unique though). So if you used your artist+song as your prioirty for each record, you could check if it already exists either:-

using startat and limit (startat your key with a limit of one, check the returned record value) OR maybe use startat and endat equal to your key and check if any value is returned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!