3

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
}
Maksym Moros
  • 499
  • 7
  • 21
  • There are often many ways to get a job done. What is the specific problem you're running into here with these tries? Are there error messages? What doesn't work the way you expect. Please edit the question to be clear. Note that map fields in Firestore documents will show up as plain JavaScript objects, so you will deal with them exactly as you would normally in JavaScript. – Doug Stevenson Apr 27 '20 at 20:49
  • Thanks Doug. Cleaned up the text a bit. The specific issues I'm running into are trying to manipulate the JS 'map' object to perform some logic. When I have the uids in a var, I can't figure out how to access or iterate the entries. – Maksym Moros Apr 27 '20 at 20:59
  • There are many ways to iterate an object in JS. It's very common. See: https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object – Doug Stevenson Apr 27 '20 at 21:16
  • ahhh casting using Object.x was the key trick. Thanks! – Maksym Moros Apr 27 '20 at 21:35

1 Answers1

6

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
  }
});
p9f
  • 601
  • 1
  • 5
  • 14