Check firebase for an existing object based on att

2020-07-26 19:40发布

问题:

I want to check my firebase to see if I already have an object stored that matches two attributes. To put this question into context, imagine an app that just stores songs, with attributes like 'artist' and 'songname' and some more, like this:

var wishlist = new Firebase('https://myurl.firebaseio.com/wishes');

wishlist.push({
   'artist': artist,
   'song': song,
   'likes': 0
});

I want to prevent object creation at this point if an object with the same artist AND songname already exists. How do I check for that? The documentation doesn't seem to provide an example for that since they only point out cases that directly reference a name. My object names are auto generated, I read them in the callback with snapshot.name();.

Can or should I do this using the security rules in the firebase backend or check for it on the client side already?

Thanks a lot for any clues :)!

回答1:

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


回答2:

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.