Sharjeel Malik
Sharjeel Malik

Reputation: 108

How to query specific data from Firebase using Cloud functions

This is my firebase data

users
 -L2yfvAU0cihwcJHqIv9
     City: "wah cantt"
     Email: "[email protected]"
     Firstname: "sharjeel"
     Lastname: "malik"
     Latitude: "74.27559833333333"
     Longtitude: "31.509099999999997"
     Phone: "03035602137"
     Username: "sharjeel089"

This is my current cloud function

exports.retreivefromdatabase = functions.https.onRequest((req,res) => {
var db = admin.database();
var ref = db.ref();

ref.on("value", function(snapshot){
res.send(snapshot.val());
});
});

This function retrieves all data from firebase database. I just want to retrieve user data in the form of key value pairs like this on the basis of username.

 {"City": "wah 
cantt","Email":"[email protected]","Firstname":"sharjeel"........}

How to do that?

Upvotes: 1

Views: 1447

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

This is one of the many ways to do this:

exports.retreivefromdatabase = functions.https.onRequest((req,res) => {
  var db = admin.database();
  var ref = db.ref();
  var username = req.params.username;

  ref.orderByChild("Username").equalTo(username).once("child_added", function(snapshot){
    res.send(snapshot.val());
  });
});

As I commented, Cloud Functions is not the easiest nor best way to learn how to interact with the Firebase Database from JavaScript. I'd recommend taking the codelab I mentioned or one of the many other tutorials out there. These allow you to simply run your code in a web page, which is a way faster way to work this out. Then once you've gotten the basics, deploying similar functionality on Cloud Functions is a much simpler step.

Upvotes: 2

Related Questions