[英]How to add Document with Custom ID to firestore in firestore 9
如何将自定义 id 添加到 firestore 文档而不是由 firebase 9 自动生成的 id?
我在将此代码转换为 firebase 9 版本时遇到问题 -
db.collection("cities").doc("LA").set({
name: "Los Angeles",
state: "CA",
country: "USA" })
您提供的示例似乎来自Firestore 的文档本身。 切换到( modular
)选项卡而不是( namespaced
)以在 V9 语法中看到相同的内容。
使用 Modular SDK 设置具有自定义 ID 的文档的语法如下(对于相同的示例):
import { doc, setDoc } from "firebase/firestore";
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
研究了很多时间后,我自己找到了解决方案
试试这个。
所以,解决方案是:
FirebaseFirestore db = FirebaseFirestore.getInstance();
// [START set_document]
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());
city.put("session", "2020-2021");
String documentID = "YOUR_CUSTOM_DOC_ID (You can also add String here)";
db.collection("YOUR_COLLECTION_PATH").document(""+documentID)
.set(city)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
Toast.makeText(add_student_info.this, "Added Successfully!", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
Toast.makeText(add_student_info.this, "Failed to add Student data!", Toast.LENGTH_LONG).show();
}
});
// [END set_document]
}
希望它现在工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.