I am trying to loop through a collection of users, which are documents, in my firestore database. The user documents I get, have subcollections within them. Within these subcollections, I want to add a document. I am currently at the point of adding the document to the subcollection, but I am being told that the collection method does not exist because userDoc is still in a promise which doesn't make any sense because when I print the id of the userDoc I get the id of the document in firestore. Error:
Uncaught (in promise) TypeError: userDoc.collection is not a function
My code is below.
async function preformSignaling() {
let users = await negDoc.collection("users").get();
for (let userDoc of users.docs) {
if (isNotAlreadyConnected(userDoc.id)) {
let newPeerConnection = new UserConnection(servers, userDoc.id);
if (
userDoc.id != sessionStorage.getItem("userID") &&
userDoc.id != "metadata"
) {
let connOfferDescription =
await newPeerConnection.userPeerConnection.createOffer();
await newPeerConnection.userPeerConnection.setLocalDescription(
connOfferDescription
);
await userDoc.collection("offer-candidates").doc("offer").set({
offer: newPeerConnection.userPeerConnection.localDescription,
});
}
peerConnections.push(newPeerConnection);
}
}
}
class UserConnection {
constructor(servers, remoteUserID) {
this.userPeerConnection = new RTCPeerConnection(servers);
this.remoteStream = new MediaStream();
this.remoteUserID = remoteUserID;
getRemoteUserID() {
return this.remoteUserID;
}
}
Concerned Code:
await userDoc.collection("offer-candidates").doc("offer").set({
offer: newPeerConnection.userPeerConnection.localDescription,
});
CodePudding user response:
The problem doesn't have anything to do with promises; you're awaiting what you're supposed to await. The issue is that userDoc
is a document snapshot (ie, the result of querying the database), and document snapshots don't have a .collection
method. They basically just have a .data()
method, and then some metadata properties (eg, .id
, .exists
)
Instead, you need to do the following:
await negDoc
.collection("users")
.doc(userDoc.id)
.collection("offer-candidates")
.doc("offer")
.set({
offer: newPeerConnection.userPeerConnection.localDescription,
});