简体   繁体   English

使用 Firebase 的服务器时间戳

[英]Server timestamp using firebase

I am working on a review/comment process and would like to be able to store each review/comment given by a user for another one in firebase, with each review/rating given at the same time being under the same timestamp.我正在研究评论/评论过程,并希望能够将用户给出的每条评论/评论存储在 firebase 中,同时给出的每条评论/评级都在相同的时间戳下。 I was using the JS function new Date().getTime() initially, and this works fine, but to ensure that users can't tamper with the value (ie by changing the date on their computer) I would like to use firebase timestamp instead.我最初使用的是 JS 函数 new Date().getTime() ,这很好用,但为了确保用户不能篡改该值(即通过更改他们计算机上的日期),我想使用 firebase 时间戳反而。

Now, I want the end product to be a map:现在,我希望最终产品是一张地图:

[chatStartTime] : {
   review : stars,
   time : chatStartTime
 }

Which I then incorporate into a firebase document using transaction.set().然后我使用 transaction.set() 将其合并到 firebase 文档中。 Now the issue is the ChatStartTime, which is supposed to represent this timestamp.现在的问题是 ChatStartTime,它应该代表这个时间戳。 I have the code:我有代码:

var chatStartTime = firebase.firestore.FieldValue.serverTimestamp();

As an aside, I am also hoping to get:顺便说一句,我也希望得到:

var chatStartTimeDate = chatStartTime.toDate();

However chatStartTimeDate leads to an error – my understanding is that this is because chatStartTime is essentially "void" until it is added to a document;然而,chatStartTimeDate 会导致错误——我的理解是,这是因为 chatStartTime 在被添加到文档之前本质上是“空的”; is there any way to get around this and use this function?有什么办法可以解决这个问题并使用这个功能吗? Also, if I just use chatStartTime for both instances, I end up with a map on the database of the form:另外,如果我只对这两个实例使用 chatStartTime,我最终会在表单的数据库上得到一个映射:

[object Object] 
  review : 4.5
  time :
        .sv: "timestamp"

Where .sv is a string type.其中 .sv 是字符串类型。 How can I solve this issue?我该如何解决这个问题? I'd like the end result to look something like (for example)我希望最终结果看起来像(例如)

 1579194722735
  review : 4.5
  time : 1579194722735

The FieldValue.serverTimestamp() value is written on the server at time of write. FieldValue.serverTimestamp()值在写入时写入服务器。 So you can't get it before the write happens.所以你不能在写发生之前得到它。 However, you can get the writeTime from the response.但是,您可以从响应中获取writeTime This should give you what you're after.这应该给你你所追求的。 Alternately, you could read the document back out after you write it to fetch the timestamp (but that seems unnecessary).或者,您可以在写入文档以获取时间戳后将其读回(但这似乎没有必要)。

myCollection
    .doc('foo')
    .create({ timestamp: FirebaseFirestore.FieldValue.serverTimestamp() })
    .then(result => {
      const serverTime: Date = result.writeTime.toDate();
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM