4

This shows a way to check if a node with a given id exists or not. However, I am inserting a node using push method with random ids. Suppose nodes have fields A, B and C. Before inserting a node with A = a1, B = b1, C = c1. I want to check if a node with this combination exists or not.

Community
  • 1
  • 1
Chor Sipahi
  • 546
  • 3
  • 10

2 Answers2

1

You can always do a read and check the properties:

function checkData(data) {
  return data.A === 'a1' && data.B === 'b1' && data.C === 'c1';
}
var ref = new Firebase('<my-firebase-app>/item');
ref.once('value', function(snap) {
  var hasCombination = checkData(snap.val());
});

But you can also write your security rules so that that combination only ever exists. Using Bolt, the Security Rules compiler, makes this even easier, because Bolt allows you to map types to paths.

type Data {
  a: String;
  b: String;
  c: String;
}

path /data is Data;

This code generates a set of validation rules that make sure that objects that only have String properties of A, B, and C are saved to the /data path.

David East
  • 31,526
  • 6
  • 67
  • 82
  • Thanks for the response. The function which you provided will it check for all the nodes?I mean item can have 10 childs with random ids and each of these 10 childs have field A, B and C. Before inserting 11th child(with A = a1, B = b1, C = c1) I need to ensure that none of the previous 10 have this. Do I need to loop over all 10? Or the function you gave will do it on its own? If yes please tell how it is doing that? – Chor Sipahi Dec 28 '15 at 19:00
1

As written in David's answer we can read and check. However he didn't mention about when we wanna check for multiple child nodes. forEach method is what will help in such case. So we can apply David's solution for each chlid using forEach.

Chor Sipahi
  • 546
  • 3
  • 10