'How to add Document with Custom ID to firestore

Is there any chance to add a document to firestore collection with custom generated id, not the id generated by firestore engine?



Solution 1:[1]

In case if you are using angularfire,

class Component{
  constructor(private afs: AngularFireStore) {} // imported from @angular/fire/firestore

  addItem() {
    this.afs.collection('[your collection]').doc('[your ID]').set({your: "document"});
  }
}

Solution 2:[2]

To expand on the accepted answer, if you ever wanted your client to generate a random ID for the doc before pushing to Firestore (assuming the same createId() function exists outside of AngularFire2)

const newId = db.createId();
db.collection("cities").doc(newId).set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

This is useful for setting the ID as a reference field in another document, even before Firestore saves anything. If you don't need to use the saved object right away, this speeds up the process by not making you wait for the ID. The set() call is now asynchronous from the pipe you might be using in Angular

Notice I didn't put id: newId in the set object, because Firestore by default doesn't save ID as a field in the doc

Solution 3:[3]

You can do it this way

// Inject AngularFirestore as dependency 
private angularFireStore: AngularFirestore // from from 'angularfire2/firestore'

// set user object to be added into the document
let user = {
  id: this.angularFireStore.createId(),
  name: 'new user'
  ...
}

// Then, finally add the created object to the firebase document
angularFireStore.collection('users').doc(user.id).set(user);

Solution 4:[4]

I'll just leave this here if anyone is looking for version 9.

This was taken from the docs.

import { doc, setDoc } from "firebase/firestore"; 

// Add a new document in collection "cities" with "LA" add id
await setDoc(doc(db, "cities", "LA"), {
  name: "Los Angeles",
  state: "CA",
  country: "USA"
});

where db is:

const firebaseApp = initializeApp(firebaseConfig)
const db = getFirestore(firebaseApp)

Solution 5:[5]

db.collection("users").document(mAuth.getUid()).set(user)

Here, the name of the collection is "users" and the document name is the user's UID

Here u need to use set not add

private void storeData(String name, String email, String phone) {

    // Create a new user with a first and last name
    Map<String, Object> user = new HashMap<>();
    user.put("name", name);
    user.put("email", email);
    user.put("phone", phone);

    // Add a new document with a generated ID
    db.collection("users").document(mAuth.getUid()).set(user)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Toasty.success(context,"Register sucess",Toast.LENGTH_SHORT).show();
        }
    });
}

Solution 6:[6]

The Code Which is given First is for JavaScript This is for Android Studio (JAVA)

Map<String, Object> city = new HashMap<>();
city.put("name", "Los Angeles");
city.put("state", "CA");
city.put("country", "USA");
//Here LA is Document name for Assigning
db.collection("cities").document("LA")
    .set(city)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "DocumentSnapshot successfully written!");
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Error writing document", e);
        }
    });

To Set ID while adding data u have to Use Set Method

If This Code is Out-Dated Then Find the New Code Here

Solution 7:[7]

This is function that creates document with data and you can choose if you want to generate id yourself or automatically. If id is provided during the function callout then the document that will be created, is going to have the id that you provided.

Modular Firebase firestore 9.+

import { getFirestore, serverTimestamp, collection, doc, setDoc, addDoc } from 'firebase/firestore/lite'
async create(id = null, data) {
    const collectionRef = collection(getFirestore(), this.collectionPath)

    const dataToCreate = {
      ...data,
      createTimestamp: serverTimestamp(),
      updateTimestamp: serverTimestamp()
    }

    const createPromise =
      id === null || id === undefined
        ? // Create doc with generated id
          await addDoc(collectionRef, dataToCreate).then(d => d.id)
        : // Create doc with custom id
          await setDoc(doc(collectionRef, id), dataToCreate).then(() => id)

    const docId = await createPromise

    return {
      id: docId,
      ...data,
      createTimestamp: new Date(),
      updateTimestamp: new Date()
    }
  }

Same function for not modular Firebase firestore( < version 9)

import { firebase } from '@firebase/app'
async create(data, id = null) {
    const collectionRef = (await firestore()).collection(this.collectionPath)
    const serverTimestamp = firebase.firestore.FieldValue.serverTimestamp()

    const dataToCreate = {
      ...data,
      createTimestamp: serverTimestamp,
      updateTimestamp: serverTimestamp
    }

    const createPromise =
      id === null || id === undefined
        ? // Create doc with generated id
          collectionRef.add(dataToCreate).then(doc => doc.id)
        : // Create doc with custom id
          collectionRef
            .doc(id)
            .set(dataToCreate)
            .then(() => id)

    const docId = await createPromise

    return {
      id: docId,
      ...data,
      createTimestamp: new Date(),
      updateTimestamp: new Date()
    }
  }

Solution 8:[8]

Create new Document with ID

  createDocumentWithId<T>(ref: string, document: T, docId: string) {
    return this.afs.collection(ref).doc<T>(docId).set(document);
  }

EX: this example with take email as ID for the document

this.fsService.createDocumentWithId('db/users', {}, credential.user.email);

Solution 9:[9]

If you want to add custom id not firestore generated then just do this:

val u:String=FirebaseAuth.getInstance().currentUser?.uid.toString() FirebaseFirestore.getInstance().collection("Shop Details").document(u).set(data)

//u is not in firestore it will create first and add data //data is whatever you want to add in firestore

Solution 10:[10]

after researching a lot of time I got a solution for this by myself

Actually, if we declare a String before and call that on hashmap it won't work.

So, the solution is:

 Map<String, Object> city = new HashMap<>();
                city.put("batch", "25");
                city.put("blood", ""+stuBlood.getText().toString());
                city.put("email", ""+stuEmail.getText().toString());
                city.put("facebook", ""+stuFacebook.getText().toString());
                city.put("gender", ""+stuGender.getText().toString());
                city.put("id", ""+stuID.getText().toString());
                city.put("image", ""+stuImage.getText().toString());
                city.put("location", ""+stuLocation.getText().toString());
                city.put("name", ""+stuName.getText().toString());
                city.put("phone", ""+stuPhone.getText().toString());
                city.put("whatsapp", ""+stuWhatsApp.getText().toString());
                city.put("telegram", ""+stuTelegram.getText().toString());

Hope it's working now

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wajahath
Solution 2
Solution 3 Jonel Dominic Brave
Solution 4 tenshi
Solution 5 Brett Caswell
Solution 6
Solution 7 Tarvo Mäesepp
Solution 8 sun sreng
Solution 9 Roheet Jadhav
Solution 10 Hasib