0
votes

I have this data structure in my firebase.

  "produtos" : {
    "3" : {
      "data" : "2017-09-21",
      "fornecedor" : {
        "cnpj" : "123234534534",
        "fantasia" : "Barreirinha"
      },
      "nNF" : 3,
      "peso" : 3,
      "precoCompra" : 6,
      "vendido" : false
    },
    "123" : {
      "data" : "2017-09-14",
      "fornecedor" : {
        "cnpj" : "123234534534",
        "fantasia" : "Barreirinha"
      },
      "nNF" : 123,
      "peso" : 23000,
      "precoCompra" : 2.21,
      "vendido" : false
    }
  }

I need to get a list of values of objects that contain the CNPJ key.

I'm using Angular, AngularFire2 and TypeScript, but I can not understand.

retrieveProdutos(cnpjFornecedor: string) {
    this.produtos = this.db.list(this.paths.pathProduto, {
      query: {
        orderByChild: 'cnpj',
        equalTo: cnpjFornecedor,
        orderByKey: true,
      }
    });
  }

How do I get this list? is returning empty.

2

2 Answers

0
votes

You can only query one field ;

query: {
  orderByChild: "vendido",
  equalTo: "false" 
}

which for example would give you all the child nodes that have their vendido child key set to false.

Also, if you want to access each child value, you could do:

this.produtos.subscribe(produtos => {

    produtos.forEach(produto => {

        console.log("produto:", produto);

        // And here you can access each produto data 

    });
});

or, depending on you access your database:

 yourRef.on("value", (snapshot) => {

       snapshot.forEach((child) => {

                var produto = child.val();

                console.log("produto nNF", produto.nNF);

        });

});
0
votes

Given your JSON, you're filtering by a nested property at a known path. This is possible by specifying the path to the property in the query:

retrieveProdutos(cnpjFornecedor: string) {
    this.produtos = this.db.list(this.paths.pathProduto, {
      query: {
        orderByChild: 'fornecedor/cnpj',
        equalTo: cnpjFornecedor
      }
    });
  }

Update: on second read you say you want to return items that have a value for nNF. In this case you can filter with:

retrieveProdutos(cnpjFornecedor: string) {
    this.produtos = this.db.list(this.paths.pathProduto, {
      query: {
        orderByChild: 'nNF',
        startAt: 0
      }
    });
  }

You'll want to note that Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. For an example of this and other approaches, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase