要将自定义Java对象上载到Firebase Firestore
,我想创建一个time
字段,该字段将在创建数据时存储服务器时间戳。怎么做?
答案 0 :(得分:0)
对于write a server-side timestamp in Firebase,您需要使用以下标记值:FieldValue.serverTimestamp()
。因此,如果您希望Java对象中的特定字段具有此值,则将该字段初始化为FieldValue.serverTimestamp()
。
public class MyObject {
public String value;
public Object timestamp = FieldValue.serverTimestamp();
}
我将timestamp
字段标记为Object
,因为(我认为)它在初次创建时将具有与从数据库读回时不同的类型。 / p>
答案 1 :(得分:-1)
首先,您必须获取服务器时间,然后才能将该时间上传到Firebase实时数据库。
您的自定义数据类:
public class ServerTime {
public String time;
public ServerTime (String time) {
this.time= time;
}
}
ServerTime object = ServerTime(timestamp); // set your time here
DatabaseReference mRef = FirebaseDatabase.getInstance()
.getReference("ServerTime").setValue(object);
答案 2 :(得分:-1)
您可以从客户端库中做到这一点。您需要创建一个Cloud函数,该函数会在将值添加到Firestore集合时触发,并将当前日期字段插入其中。 More about Firebase cloud functions and Firestore triggers