将服务器时间戳字段添加到要添加的对象中 [英] Adding Server Timestamp field to the Object which being added
问题描述
我有一个Challenge
对象,该对象具有它自己的属性,并且可以像这样将其成功添加到数据库中:
I have a Challenge
object, which has it's own properties and I'm able to add it to the database successfully like this:
DocumentReference challengeRef=usersRef.document(loggedUserEmail).collection("challenges_feed").
document(callengeID);
challengeRef.set(currentChallenge);
这是数据库中的样子:
我想在数据库中创建一个名为latestUpdateTimetamp
的新字段(在此挑战下).这是应该的样子(我已经手动添加了):
I'd like to make a new field in the database (under this challenge) which called latestUpdateTimetamp
. This is how it should look like (I have added it manually):
我试图像这样在object
的constructor
中设置它:
I have tried to set it in the constructor
of the object
like this:
private Map<String,String> latestUpdateTimestamp;
public Challenge(String id, String senderName, String senderEmail) {
this.senderName=senderName;
this.senderEmail = senderEmail;
this.latestUpdateTimestamp= ServerValue.TIMESTAMP;
}
但这就是我在database
中得到的:
But this is what I get in the database
:
我正在尝试在同一调用中将latestUpdateTimestamp
添加到Challenge
并将Challenge
对象本身添加到数据库.有可能吗?
I'm trying to add the latestUpdateTimestamp
to the Challenge
and the Challenge
object itself to the database at the same call. Is it possible?
我可以以某种方式将此timestamp
作为属性添加到此object
之前吗?
Can I somehow add this timestamp
as a property to this object
before adding it?
我知道我可以打一个新电话并添加此字段,但是我想知道是否有可能一次.
I know I'm able to make a new call and add this field, but I'm wondering if it's possible at once.
推荐答案
是的,可以使用Map
.首先,根据官方文档,使用如下所示的注释将是必要的:
Yes you can, using a Map
. First of all, according to official docs it will be necessary to use an annotation that looks like this:
@ServerTimestamp Date time;
用于标记要用服务器时间戳填充的日期"字段的注释.如果正在写入的POJO包含@ServerTimestamp注释字段的null,它将被服务器生成的时间戳替换.
Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.
这是如何同时用服务器时间戳更新latestUpdateTimestamp
字段和使用所需的值更新challangeId
的方法.
This is how you can update the latestUpdateTimestamp
field with the server timestamp and the challangeId
with the desired value at the same time.
DocumentReference senderRef = challengeRef
.document(loggedUserEmail)
.collection("challenges_feed")
.document(callengeID);
Map<String, Object> updates = new HashMap<>();
updates.put("latestUpdateTimestamp", FieldValue.serverTimestamp());
updates.put("challangeId", "newChallangeId");
senderRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}
这篇关于将服务器时间戳字段添加到要添加的对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!