196

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

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Harvey Dent
  • 2,033
  • 2
  • 11
  • 7

11 Answers11

370

To use a custom ID you need to use .set, rather than .add

This creates a document with the ID "LA":

db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

This is taken from the official docs here

Finlay Percy
  • 6,763
  • 4
  • 22
  • 28
  • 1
    What if I want to add to the doc `"LA"`? This won't work: `.doc("LA").add({...})` Please tell how can I do that. – Shubham Kushwah Jan 21 '19 at 20:29
  • 16
    `.add()` is equivalent to `.doc().set()` – roshnet Sep 01 '20 at 16:13
  • 4
    If we want to add custome id then we have to use .doc().set() instead of add() –  Jan 02 '21 at 17:55
  • 3
    If you are using set() method to update document fields then be careful, it kills non-updated fields in the document. eg. I had 6 fields in a document and I updated only 4 fields then set() method removed 2 fields and their information from that document on firestore. Just sharing my experience. Thanks. – Kamlesh Jun 14 '21 at 13:44
  • 1
    @Kamlesh Just add `{ merge: true }` after your doc object to keep existing not updated fields. – Greg B. Jan 27 '22 at 13:05
28

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"});
  }
}
Wajahath
  • 2,827
  • 2
  • 28
  • 37
Papa Kojo
  • 793
  • 8
  • 18
26

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" as 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)
tenshi
  • 508
  • 4
  • 12
21

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

5

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);
5

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()
    }
  }
Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92
  • Thanks! this is the only answer that is still valid with the new modular Firebase @angular/firebase – Dan M Aug 21 '23 at 04:06
4

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();
        }
    });
}
Brett Caswell
  • 1,486
  • 1
  • 13
  • 25
Deven
  • 684
  • 7
  • 10
2

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

Sanjith
  • 49
  • 3
1

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);
sun sreng
  • 587
  • 6
  • 7
0

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

0

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

Hasib
  • 1
  • 1