【问题标题】:Counter in Firestore database in FirebaseFirebase 中 Firestore 数据库中的计数器
【发布时间】:2020-05-13 18:20:22
【问题描述】:

我正在创建一个 Android 应用程序,其中我必须为组织和个人用户记录 YTD、MTD 和每日记录。我尝试了每次保存记录的方法,我有一个计数器集合,可以保存像

这样的数据
ORG_ORGID_2020 (for YTD)
ORG_ORGID_202005 (for MTD)
ORG_ORGID_20200513 (for Daily data)

ORG_USER1_2020 (for YTD)
ORG_USER2_202005 (for MTD)
ORG_USER3_20200513 (for Daily data)

这样我在获取报告时就不必阅读很多文档。现在为了尽量减少读取,我将属性保存在上述文档中(org_ID、年份(即 2020)、年月(即 202005)等。我以计数器对象的形式保存上述文档

public class Counter {

@DocumentId
private String id;
private long count;
private String dealerId;
private String userId;
private String year;
private String yearMonth;
private String yearMonthDate;

}

当我必须更新计数器时不会出现问题。我尝试使用

private FieldValue count;

并且能够正确使用更新计数

Counter counter = new Counter();
    counter.setCount(FieldValue.increment(1));
    counter.setDealerId(intentDealer.getId());
    counter.setYear(strFullYear);
    batch.set(dealerYtdColRef, counter, SetOptions.merge());

但是当我尝试获取记录时,我得到了

java.lang.RuntimeException:在类 com.google.firebase.firestore.FieldValue 上找不到要序列化的属性

如果我将字段更改为

private long count;

我不明白如何更新计数器。我必须与计数器一起设置所有字段。我也尝试使用 .update 方法,但是当文档不存在并且必须第一次创建时它会出错。

我怎样才能正确管理计数器?我正在从仅应用程序而不是功能中做对应的部分,因为我试图让应用程序仅在免费的 firebase 层中工作。

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    您的代码中的问题是以下代码行:

    counter.setCount(FieldValue.increment(1));
    

    您的count 属性在您的Counter 类中定义为long 类型。当你使用setCount() 方法来设置它的值时,你应该传递一个长值作为参数,但实际上你没有。以下声明:

    FieldValue.increment(1)
    

    返回 FieldValue 类型的对象,而不是 long,因此会出现错误。要将 count 属性的值自动加一,请使用以下代码行:

    Map<String, Object> updateCount = new HashMap<>();
    updateCount.put("count", FieldValue.increment(1));
    yourDocRef.set(updateCount, SetOptions.merge());
    

    【讨论】:

    • Alex,当我使用 FieldValue 类型的计数时,出现上述错误 java.lang.RuntimeException: No properties to serialize found on class com.google.firebase.firestore.FieldValue
    • 是的,这是预期的行为,因为FieldValue 类是不可可序列化的。您不应该更改应该保留原样的字段类型,并在我的回答中使用该解决方案。试过了吗,有效果吗?
    【解决方案2】:

    最后,根据 Alex 的建议,我使用地图值,但同时,我将代码移到了 google。如果我执行错误,请告诉我。不过好像还可以

    const functions = require('firebase-functions');
    
    // The Firebase Admin SDK to access the Firebase Realtime Database.
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    // // Create and Deploy Your First Cloud Functions
    // // https://firebase.google.com/docs/functions/write-firebase-functions
    //
    // exports.helloWorld = functions.https.onRequest((request, response) => {
    //  response.send("Hello from Firebase!");
    // });
    
    const db = admin.firestore();
    // [START_EXCLUDE]
    const settings = { timestampsInSnapshots: true };
    db.settings(settings);
    // [END_EXCLUDE]
    
    // [START aggregate_function]
    exports.aggregateEnquiries = functions.firestore
        .document('enquiries/{id}')
        .onWrite(async (change, context) => {
    
            if (!change.before.exists) {
                // New document Created : add one to count
    
                var dealerId = change.after.data().dealerId;
                var userId = change.after.data().assignedTo;
                var date = change.after.data().createdDt.toDate();
                var day = date.getDate();
                var month = date.getMonth() + 1;
                var year = date.getFullYear();
                var yearMonth = String(year) + (month < 10 ? "0" + month : month);
                var yearMonthDate = yearMonth + (day < 10 ? "0" + day : day);
    
                try {
                    return await db.collection("dealers").doc(dealerId)
                        .get()
                        .then((doc) => {
                            if (doc !== null && doc.exists) {
                                const increment = admin.firestore.FieldValue.increment(1);
    
                                db.collection("enquiries_agg")
                                    .doc("D_" + dealerId + "_" + year)
                                    .set({ "count": increment }, { merge: true });
    
                                db.collection("enquiries_agg")
                                    .doc("D_" + dealerId + "_" + monthYear)
                                    .set({ "count": increment }, { merge: true });
    
                                db.collection("enquiries_agg")
                                    .doc("U_" + userId + "_" + year)
                                    .set({
                                        "count": increment,
                                        "dealerId": dealerId,
                                        "userId": userId,
                                        "reference": String(year)
                                    }, { merge: true });
    
                                db.collection("enquiries_agg")
                                    .doc("U_" + userId + "_" + yearMonth)
                                    .set({
                                        "count": increment,
                                        "dealerId": dealerId,
                                        "userId": userId,
                                        "reference": String(yearMonth)
                                    }, { merge: true });
    
                                db.collection("enquiries_agg")
                                    .doc("U_" + userId + "_" + yearMonthDate)
                                    .set({
                                        "count": increment,
                                        "dealerId": dealerId,
                                        "userId": userId,
                                        "reference": String(yearMonthDate)
                                    }, { merge: true });
                            } else {
                                console.log("error in aggregare entries.");
                            }
    
                            return null;
                        });
                }
                catch (error) {
                    console.log("Error getting documents: ", error);
                    throw new Error("Profile doesn't exist : " + error);
                }
            } else if (change.before.exists && change.after.exists) {
                // Updating existing document : Do nothing
            } else if (!change.after.exists) {
                // Deleting document : subtract one from count
            }
    
            return null;
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2019-11-01
      • 2020-02-24
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多