Java Firebase中Firestore数据库中的计数器

Java Firebase中Firestore数据库中的计数器,java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,我正在创建一个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_202

我正在创建一个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)
这样我在获取报告时就不必阅读很多文档。现在,为了尽量减少读取,我将属性保存在上述文档中(组织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层中工作。

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

counter.setCount(FieldValue.increment(1));
您的
count
属性在
Counter
类中定义为long类型。当您使用
setCount()
方法设置其值时,您应该将long值作为参数传递,但实际上没有。以下语句:

FieldValue.increment(1)
返回类型为且不长的对象,因此出现错误。若要将count属性的值以原子方式递增1,请使用以下代码行:

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

最后,根据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;
    });
const functions=require('firebase-functions');
//使用Firebase管理SDK访问Firebase实时数据库。
const admin=require('firebase-admin');
admin.initializeApp();
////创建并部署您的第一个云功能
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
//exports.helloWorld=functions.https.onRequest((请求,响应)=>{
//回复。发送(“来自Firebase的你好!”);
// });
const db=admin.firestore();
//[开始时不包括]
常量设置={timestampsInSnapshots:true};
数据库设置(设置);
//[完]
//[启动聚合函数]
exports.aggregateRequesties=functions.firestore
.document('inquiries/{id}'))
.onWrite(异步(更改、上下文)=>{
如果(!change.before.exists){
//已创建新文档:将一个添加到计数
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();
变量yearMonth=字符串(年)+(月<10?“0”+月:月);
var yearMonthDate=yearMonth+(天<10?“0”+天:天);
试一试{
退货等待数据库收款(“经销商”).doc(dealerId)
.get()
。然后((doc)=>{
如果(doc!==null&&doc.exists){
常量增量=admin.firestore.FieldValue.increment(1);
db.收款(“查询和汇总”)
.doc(“D+dealerId+”年)
.set({“count”:increment},{merge:true});
db.收款(“查询和汇总”)
.doc(“D+dealerId+monthYear”)
.set({“count”:increment},{merge:true});
db.收款(“查询和汇总”)
.doc(“U+userId+”年)
.设置({
“计数”:增量,
“dealerId”:dealerId,
“userId”:userId,
“参考”:字符串(年)
},{merge:true});
db.收款(“查询和汇总”)
.doc(“U_”+用户ID+“_”+年-月)
.设置({
“计数”:增量,
“dealerId”:dealerId,
“userId”:userId,
“reference”:字符串(yearMonth)
},{merge:true});
db.收款(“查询和汇总”)
.doc(“U_U”+userId+“uu”+yearMonthDate)
.设置({
“计数”:增量,
“dealerId”:dealerId,
“userId”:userId,
“参考”:字符串(yearMonthDate)
},{merge:true});
}否则{
log(“aggregare条目中的错误”);
}
返回null;
});
}
捕获(错误){
log(“获取文档时出错:”,错误);
抛出新错误(“配置文件不存在:“+错误”);
}
}else if(change.before.exists&&change.after.exists){