Add timestamp in Firestore documents

心不动则不痛 提交于 2020-05-10 07:12:53

问题


I'm newbie to Firestore. Firestore docs says...

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

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

So do I have to create key name as timestamp in document? Or created is suffice to fulfill above statement from Firestore documentation.

{
    "created": 1534183990,
    "modified": 1534183990,
    "timestamp":1534183990
}

回答1:


Whatever you want to call it is fine afaik. Then you can use orderByChild('created').

I also mostly use firebase.database.ServerValue.TIMESTAMP when setting time

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



回答2:


Use firestore Timestamp class, firebase.firestore.Timestamp.now().

Since firebase.firestore.FieldValue.serverTimestamp() does not work with add method from firestore. Reference




回答3:


For Firestore

ref.doc(key).set({
  created: firebase.firestore.FieldValue.serverTimestamp()
})



回答4:


The documentation isn't suggesting the names of any of your fields. The part you're quoting is just saying two things:

  1. The automatically generated document IDs for Firestore don't have a natural time-based ordering like they did in Realtime Database.
  2. If you want time-based ordering, store a timestamp in the document, and use that to order your queries. (You can call it whatever you want.)



回答5:


Try this one for Swift 4 Timestamp(date: Date())

let docData: [String: Any] = [
"stringExample": "Hello world!",
"booleanExample": true,
"numberExample": 3.14159265,
"dateExample": Timestamp(Date()),
"arrayExample": [5, true, "hello"],
"nullExample": NSNull(),
"objectExample": [
    "a": 5,
    "b": [
        "nested": "foo"
    ]
]
]
db.collection("data").document("one").setData(docData) { err in
if let err = err {
    print("Error writing document: \(err)")
} else {
    print("Document successfully written!")
}
}



回答6:


The way it worked with me, is just taking the timestamp from the snapshot parameter snapshot.updateTime

exports.newUserCreated = functions.firestore.document('users/{userId}').onCreate(async (snapshot, context) => {
console.log('started!     v1.7');
const userID = context.params['userId'];

firestore.collection(`users/${userID}/lists`).add({
    'created_time': snapshot.updateTime,
    'name':'Products I ♥',
}).then(documentReference => {
    console.log("initial public list created");
    return null;
  }).catch(error => {
    console.error('Error creating initial list', error);
    process.exit(1);
});

});




回答7:


This solution worked for me:

Firestore.instance.collection("collectionName").add({'created': Timestamp.now()});

The result in Cloud Firestore is: Cloud Firestore Result




回答8:


Swift 5.1

...
"dateExample": Timestamp(date: Date()),
...


来源:https://stackoverflow.com/questions/51846914/add-timestamp-in-firestore-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!