如何将具有自定义ID的文档添加到Firestore


Answers:


217

要使用自定义ID,您需要使用.set,而不是.add

这将创建一个ID为“ LA”的文档:

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

这取自此处的官方文档


1
如果要添加到文档中"LA"怎么办?这行不通:.doc("LA").add({...})请告诉我该怎么做。
Shubham Kushwah

3
.add()等效于.doc().set()
roshnet

如果要添加自定义ID,则必须使用.doc()。set()而不是add()
Bilal Yaqoob


7

为了扩展接受的答案,如果您希望客户端在推送到Firestore之前为文档生成随机ID(假设createId()AngularFire2外部存在相同的功能)

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

即使在Firestore保存任何内容之前,这对于将ID设置为另一个文档中的参考字段也很有用。如果不需要立即使用保存的对象,则无需等待ID,从而加快了处理速度。set()现在,该调用从您可能在Angular中使用的管道是异步的

请注意,我没有放入id: newIdset对象,因为Firestore默认不会将ID保存为文档中的字段


3

你可以这样

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

1

db.collection(“ users”)。document(mAuth.getUid())。set(user)

在这里,集合的名称是"users",文档名称是用户的UID

这里ü需要使用setadd

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();
        }
    });
}

1

创建具有ID的新文档

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

例如:此示例以电子邮件作为文档的ID

this.fsService.createDocumentWithId('db/users', {}, credential.user.email);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.