0

Below is my working GET API, however it is using admin.firestore.

As I am a new programmer, I am having difficulties incorporating the Authentication portion

app.get("/", async (req, res) => {
  const snapshot = await admin.firestore().collection("users").get();
  

  let user = [{records:[]}];
  
  snapshot.forEach((doc) => {
    let id = doc.id;
    let data = doc.data();
    
    users.records.push({ id, ...data });
  });

  res.status(200).send(JSON.stringify(users));
  

});

What I hope to achieve is that users can only access their own database hopefully something like this

app.get("/", async (req, res) => {
  const snapshot = await [user uid's reference].collection([grab user's uid and insert here]).get();
  

  let [insert user's uid here] = [{records:[]}];
  
  snapshot.forEach((doc) => {
    let id = doc.id;
    let data = doc.data();
    
    [insert user's uid here].records.push({ id, ...data });
  });

  res.status(200).send(JSON.stringify([insert user's uid here]));
  

});
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Aaron
  • 1

1 Answers1

0

The user is not an object but an array, so you cannot use user.records:

// This is invalid
let users = [{records:[]}];
console.log(users.records)

// This is valid
let users = {records: []}
console.log(users.records) // []

You can directly use map() on the QuerySnapshot:

app.get("/", async (req, res) => {
  // Get a QuerySnapshot of users collection
  const snapshot = await admin.firestore().collection("users").get();
  
  // Map an array containing user data
  const users = snapshot.docs.map(d => ({id: d.id, ...d.data()}))

  // return the response
  return res.status(200).send(JSON.stringify(users));
});
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84