0

How can I choose the id document that I want to use :

firebase.firestore().collection("Users").doc(firebase.auth().currentUser.uid).collection("tasks").add({task:task.taskname,category:task.category})

Here, I create a randomly id document but I want to choose one (I mean the id of the document in the collection tasks)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user123456
  • 171
  • 11

2 Answers2

0

someCollectionRef.add(/* data */) is an alias for someCollectionRef.doc().set(/* data */).

So to specify your own ID, just use:

yourCollectionRef.doc(/* your id */).set(/* your data */);
firebase.firestore()
  .collection("Users")
  .doc(firebase.auth().currentUser.uid)
  .collection("tasks")
  .doc(/* your custom ID here */)
  .set({
    task: task.taskname,
    category: task.category
  })
  .then(() => console.log('success!'))
  .catch((err) => console.error('failed to set doc data!', err));

To place the document ID in the document, you can split this chain into two parts as below. Unless you plan on using Collection Group queries, you could use FieldPath.documentId() to query documents by their ID instead without needing to store it in the document.

const myTaskDocRef = firebase.firestore()
  .collection("Users")
  .doc(firebase.auth().currentUser.uid)
  .collection("tasks")
  .doc(/* your custom ID here */);

myTaskDocRef
  .set({
    id: myTaskDocRef.id,
    task: task.taskname,
    category: task.category
  })
  .then(() => console.log('success!'))
  .catch((err) => console.error('failed to set doc data!', err));
samthecodingman
  • 23,122
  • 4
  • 30
  • 54
-1

Adding a document using .add() returns a document reference object

So using the following code from the documentation here, this is the code you want:

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});

docRef.id holds the id of the document you added.

Tom Walsh
  • 119
  • 2
  • 12