I am new, let me know if anymore information is needed!
I am trying to integrate MessageBird with Firestore. It is writing everything to the database okay except for the "to" field which takes a phone number. I am logging the number and it is being output correctly in the console, except in my Firestore it is being stored as undefined
. If anyone can provide any insight as to why this is, that would be greatly appreciated. I have been stuck for some while. (Attached part of function where issue arises and screenshot of console)
I originally tried without using await
on the doc.data()?.phoneNum
line and just received [object Promise]
. Now that it is printing in console I know this has nothing to do with it. Please help!
admin.auth().listUsers().then((res) => {
res.users.forEach((userRecord) => {
try {
const dbRef = firestore()
.collection("collection").doc(userRecord.uid)
.collection("collection").doc(document);
dbRef.get().then((context) => {
if (context.exists) {
firestore()
.collection("collection")
.doc(userRecord.uid).get()
.then(async (doc) => {
number = await doc.data()?.field1;
console.log("Sending message to: " + number);
});
firestore().collection("collection")
.doc()
.create({
channelId: "id",
type: "text",
content: {
text: "message",
},
to: `${number}`,
});
functions.logger.log("SUCCESSFULLY SENT TO DB");
} else {
// console.log("**Unviable user**");
}
});
} catch (error) {
console.log(error);
}
});
});
The promises doesn't seem to handled properly. .data()
does not return a promise so you don't need an await
there. Also I don't see the var 'number'
declared anywhere so that'd be undefined. You can try running the following code:
admin.auth().listUsers().then(async (res) => {
try {
for (const userRecord in res) {
const dbRef = firestore()
.collection("collection").doc(userRecord.uid)
.collection("collection").doc(document);
const context = await dbRef.get()
if (context.exists) {
const number = (await firestore().collection("collection").doc(userRecord.uid).get()).data().field1
console.log("Sending message to: " + number);
await firestore().collection("collection").add({
channelId: "id",
type: "text",
content: {
text: "message",
},
to: `${number}`,
});
functions.logger.log("SUCCESS");
} else {
// console.log("**Unviable user**");
}
}
} catch (error) {
}
});
Also forEach
doesn't wait for promises to resolve so I've used a for-in loop.