![](/img/trans.png)
[英]Firestore: How can I create a subcollection in Firestore without having to add a document already
[英]How can I increase the value of a Firestore subcollection-document-field?
所以,我正在開發一個 Android 應用程序,我嘗試做的是通過按下按鈕將字段的值增加 1。 基本上,我有一個用戶集合,每個用戶都有一個帖子子集合,每個帖子都有一個名為“申請人”的數字字段,我用它來計算有多少人申請了一份工作。
問題是我找不到查詢確切文檔字段的方法,因為我無法以編程方式獲取文檔 ID。 我一直試圖通過搜索其標題來識別該帖子,但沒有運氣。 當我運行代碼時,它不會拋出任何錯誤,應用程序也不會崩潰,但我的數據庫中仍然沒有任何變化。
這是我的數據庫結構:
public void executeTransaction(int position){
db.runTransaction(new Transaction.Function<Void>() {
@Nullable
@Override
public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
db.collectionGroup("posts").whereEqualTo("title", list.get(position).getTheTitle()).get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
DocumentReference postRef = usersRef.document("posts");
DocumentSnapshot postSnapshot = null;
try {
postSnapshot = transaction.get(postRef);
} catch (FirebaseFirestoreException e) {
e.printStackTrace();
}
long newApplicants = postSnapshot.getLong("applicants") + 1;
transaction.update(postRef, "applicants", newApplicants);
}
});
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(context, "You have applied to this job!", Toast.LENGTH_SHORT).show();
}
});
這是當您點擊“應用”按鈕時運行的方法。 參數 'position' 只是帖子存儲在本地ArrayList<Post> list
。
我怎樣才能簡單地增加職位的applicants
價值?
正確的方法是使用事務(單擊此處轉到文檔)。 基本上,文檔中詳細介紹了它們的工作方式:
使用 Cloud Firestore 客戶端庫,您可以將多個操作組合到一個事務中。 當您想根據字段的當前值或某個其他字段的值更新字段的值時,事務非常有用。
而且您正在以正確的方式使用事務,但不是在最好的情況下。 由於您只想更新一個值,事務可能會使您的數據庫工作負擔過重。 一個簡單的增量方法將使用FieldValue.increment()完成工作:
DocumentReference postRef = db.collection("users").document(userId).collection("posts").document(postId);
// Atomically increment the population of the city by 50.
washingtonRef.update("applicants", FieldValue.increment(50));
您需要擁有要更新的帖子的 ID。
要解決您剛剛編輯Post
類並添加以下內容的問題:
string id;
public void setId(string id) {
this.id = id;
}
public string getId() {
return id;
}
當您收到帖子時,只需執行以下操作(也就是如何獲取帖子 ID):
for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) {
Post post = new Post();
post.setId(documentSnapshot.getId());
post.setTitle(documentSnapshot.getString("title"));
post.setApplicants(documentSnapshot.getLong("applicants")); ... list.add(post);
}
notifyDataSetChanged();
在更新applicants
字段時,要獲取文檔 ID 只需執行以下操作:
string postId = post.getId();
然后繼續您的正常代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.