在Firestore文档中添加时间戳

Vic*_*kor 8 firebase google-cloud-firestore

我是Firestore的新手。Firestore文档说...

重要提示:与Firebase实时数据库中的“推送ID”不同,Cloud Firestore自动生成的ID不提供任何自动排序。如果希望能够按创建日期订购文档,则应将时间戳记存储为文档中的字段。

参考:https : //firebase.google.com/docs/firestore/manage-data/add-data

那么我是否必须像timestamp文档中那样创建密钥名称?或者created足以满足Firestore文档中的上述要求。

{
    "created": 1534183990,
    "modified": 1534183990,
    "timestamp":1534183990
}
Run Code Online (Sandbox Code Playgroud)

小智 42

使用 firestore Timestamp 类,firebase.firestore.Timestamp.now().

由于firebase.firestore.FieldValue.serverTimestamp()不适add用于来自 firestore 的方法。参考

  • 谢谢!不要忘记 index.js 顶部的 `const firebase = require('firebase-admin')` 和 package.json 中的依赖项 `firebase-admin` (2认同)

Ven*_*tra 10

对于 Firestore

ref.doc(key).set({
  created: firebase.firestore.FieldValue.serverTimestamp()
})
Run Code Online (Sandbox Code Playgroud)


Sac*_*rab 9

任何您想称呼的都是很好的afaik。然后,您可以使用orderByChild('created')。

设置时间时,我也大多使用firebase.database.ServerValue.TIMESTAMP

ref.child(key).set({
  id: itemId,
  content: itemContent,
  user: uid,
  created: firebase.database.ServerValue.TIMESTAMP 
})
Run Code Online (Sandbox Code Playgroud)

  • 在 firestore 中要获取时间戳,您应该使用 `firebase.firestore.FieldValue.serverTimestamp()` 而不是 `firebase.database.ServerValue.TIMESTAMP` (35认同)
  • 在 Firestore 中使用 firebase.database.ServerValue.TIMESTAMP 不起作用: (2认同)

Joh*_*omi 7

使用 FIRSTORE 的实时服务器时间戳

import firebase from "firebase/app";

const someFunctionToUploadProduct = () => {

       firebase.firestore().collection("products").add({
                name: name,
                price : price,
                color : color,
                weight :weight,
                size : size,
                createdAt : firebase.firestore.FieldValue.serverTimestamp()
            })
            .then(function(docRef) {
                console.log("Document written with ID: ", docRef.id);
            })
            .catch(function(error) {
                console.error("Error adding document: ", error);
            });

}
Run Code Online (Sandbox Code Playgroud)

您只需要导入“ firebase ”,然后在需要的地方调用 firebase.firestore.FieldValue.serverTimestamp() 即可。不过要小心拼写,它的“ serverTimestamp() ”。在此示例中,它在上传到 firestore 的产品集合时为“ createdAt ”提供时间戳值。


Don*_*ghn 6

没错,就像大多数数据库一样,Firestore 不存储创建时间。为了按时间对对象进行排序:

选项 1:在客户端上创建时间戳(不保证正确性):

db.collection("messages").doc().set({
  ....
  createdAt: firebase.firestore.Timestamp.now()
})
Run Code Online (Sandbox Code Playgroud)

这里最大的警告是Timestamp.now()使用本地机器时间。因此,如果这是在客户端计算机上运行,​​则无法保证时间戳是准确的。如果您在服务器上设置此设置,或者保证顺序不是那么重要,则可能没问题。

选项 2:使用时间戳标记:

db.collection("messages").doc().set({
  ....
  createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
Run Code Online (Sandbox Code Playgroud)

时间戳标记是一个令牌,它告诉 Firestore 服务器在第一次写入时设置时间服务器端。

如果您在写入之前读取哨兵(例如,在侦听器中)它将为 NULL,除非您像这样阅读文档:

doc.data({ serverTimestamps: 'estimate' })
Run Code Online (Sandbox Code Playgroud)

使用以下内容设置您的查询:

// quick and dirty way, but uses local machine time
const midnight = new Date(firebase.firestore.Timestamp.now().toDate().setHours(0, 0, 0, 0));

const todaysMessages = firebase
  .firestore()
  .collection(`users/${user.id}/messages`)
  .orderBy('createdAt', 'desc')
  .where('createdAt', '>=', midnight);
Run Code Online (Sandbox Code Playgroud)

请注意,此查询使用本地机器时间 ( Timestamp.now())。如果您的应用在客户端上使用正确的时间真的很重要,您可以利用 Firebase 的实时数据库的此功能:

const serverTimeOffset = (await firebase.database().ref('/.info/serverTimeOffset').once('value')).val();
const midnightServerMilliseconds = new Date(serverTimeOffset + Date.now()).setHours(0, 0, 0, 0);
const midnightServer = new Date(midnightServerMilliseconds);
Run Code Online (Sandbox Code Playgroud)