Maksym Moros
Maksym Moros

Reputation: 529

Firebase Functions: Node.js: Iterate map stored in firebase document field

I am struggling to find documentation on using maps pulled from firebase in function triggers I'm building using Node.js. Everytime I find example code, it uses functions that my index.js file does not understand.

Example db structure:
db.collection('users').doc('abc')
let 'abc' hold one field called 'uids' which is a Map of String, bool

I want to iterate over 'uids'map in my Firebase trigger function to update all elements that have value "false"

I can't figure out the appropriate way to do any manipulations/logic using maps in my index.js.

These are two of the more coherent snippets I've tried, found online:

db.collection('users').doc('abc').get().then((doc) => {
  var uids = doc.data().uids;

//try 1
  uids.forEach((value, key, map) => {
    //do stuff
  });

//try 2
  for (var uid in uids) {
    if (uid.val() == false)
      //do stuff
  }
});

When searching for specific syntax regarding my index.js code, am I wrongly understanding that this is a Node.js file? I don't understand why I'm finding tens of ways to do the same thing. It seems totally random solutions are posted everywhere that don't work in my file.

SOLUTION:: Thanks for the comments and answer to help solve this. I was able to cast the firebase map using "Object.elemets(uids)" to extrace the keys and values.

for (let [key, value] of Object.elements(uids)) {
  //do stuff
}

Upvotes: 3

Views: 1791

Answers (1)

p9f
p9f

Reputation: 631

Can you try:

db.collection('users').doc('abc').get().then((doc) => {
  var uids = doc.data().uids;
  for (var uid of Object.keys(uids)) {
    console.log(uid, uids[uid]); // key, value
  }
});

Upvotes: 6

Related Questions