Skip to content
Advertisement

Trying to pass variable in fieldname when storing field to firestore

So basically I am trying to make the field name in this loop be EmailBody1, EmailBody2, etc.


 var all = _.find(item.parts, { which: "TEXT" });
            var html = all.body;
            console.log(html);
            let z = 0;
            for (z = 0; z < 40; z++) {

              // eslint-disable-next-line promise/no-nesting
              db.collection("Users")
                .doc("6IzsLbD4r4R5RXdGB5BQy6xq8Dc2")
                .set({
                  EmailBody: html,
                })
                .then(() => {
                  console.log("Doc successful");
                  return null;
                })

                .catch((error) => {
                  console.error("Error writing doc", error);
                });
            }
          });

          return null;
        });
    });
  });
}


but I have tried a few different ways like making the field name itself a variable or doing EmailBody[z] or EmailBody{z} but nothing I try seems to be working and I cannot find much info online on how to do this. Any help would be much appreciated <3

Advertisement

Answer

Two ways:

for (z = 0; z < 40; z++) {
  var obj = {};
  obj["EmailBody"+z] = html;

  db.collection("Users")
    .doc("6IzsLbD4r4R5RXdGB5BQy6xq8Dc2")
    .set(obj)
    .then(() => {
      console.log("Doc successful");
      return null;
    })

    .catch((error) => {
      console.error("Error writing doc", error);
    });
}

Or (I think):

for (z = 0; z < 40; z++) {

  // eslint-disable-next-line promise/no-nesting
  db.collection("Users")
    .doc("6IzsLbD4r4R5RXdGB5BQy6xq8Dc2")
    .set({
      ["EmailBody"+z]: html,
    })
    .then(() => {
      console.log("Doc successful");
      return null;
    })

    .catch((error) => {
      console.error("Error writing doc", error);
    });
}
Advertisement