LostTexan
LostTexan

Reputation: 891

Pass variable into collection(collectionName).doc(docName)

I am creating a cloud firestore function. The last step I need for now is using the userId to retrieve a document.

Here I get the userId const userId = snap.data().userId; <<< THIS WORKS console.log('A new transaction has been added');

Here I want insert the value from userId to retrieve the correct document.

const deviceDoc = db.collection('device').doc(**userId**); <<< THIS IS THE PROBLEM

const deviceData = await deviceDoc.get();
const deviceToken = deviceData.data().token;

I don't know how to use the variable, userId, to insert the value into the .doc(userId) to get the data.

If userId = 12345 I want the line to look like this:

const deviceDoc = db.collection('device').doc('12345');

I have tried .doc('userId'), .doc('${userId}'), as well as other things. None of these work.

How do I do this?

Upvotes: 0

Views: 320

Answers (1)

Jason Berryman
Jason Berryman

Reputation: 4908

As Puf has responded, you can simply use doc(userId). The rest of your code looks fine, so maybe the document you are getting doesn't exist. Try the following:

const deviceRef = db.collection('device').doc(userId);
// you can shorten this to >> const deviceRef = db.doc(`device/${userId}`);

try {
  const deviceDoc = await deviceRef.get();
  if (!deviceDoc.exists) {
    console.log(`The document for user ${userID} does not exist`);
  } else {
    const {token} = deviceDoc.data();
    console.log('The token is:', token);
  }
}
catch (err) {
  console.error(err);
}

Upvotes: 1

Related Questions