代码之家  ›  专栏  ›  技术社区  ›  Vicky Thakor

在Firestore文档中添加时间戳

  •  2
  • Vicky Thakor  · 技术社区  · 7 年前

    我是消防队的新手。Firestore docs说。。。

    :与Firebase实时数据库中的“推送id”不同,Cloud Firestore自动生成的id不提供任何自动排序。如果您想按创建日期订购文档, 您应该将时间戳作为字段存储在文档中。

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

    所以我必须创建密钥名为 timestamp 在文件里?或者 created

    {
        "created": 1534183990,
        "modified": 1534183990,
        "timestamp":1534183990
    }
    
    4 回复  |  直到 7 年前
        1
  •  12
  •   Saccarab    7 年前

    你想叫什么都行。然后可以使用orderByChild('created')。

    在设置时间时,我也主要使用firebase.database.ServerValue.TIMESTAMP

    ref.child(key).set({
      id: itemId,
      content: itemContent,
      user: uid,
      created: firebase.database.ServerValue.TIMESTAMP 
    })
    
        2
  •  3
  •   Venkat Kotra    6 年前

    用于Firestore

    ref.doc(key).set({
      created: firebase.firestore.FieldValue.serverTimestamp()
    })
    
        3
  •  2
  •   Doug Stevenson    7 年前

    文档没有建议任何字段的名称。你引用的是两件事:

    1. 自动生成的Firestore文档id不像在实时数据库中那样具有自然的基于时间的顺序。
    2. 如果您想要基于时间的排序,请在文档中存储时间戳,并使用它对查询进行排序。(你想怎么叫都行。)
        4
  •  2
  •   johnson lai    6 年前

    firebase.firestore.Timestamp.now() .

    firebase.firestore.FieldValue.serverTimestamp() 不适用于 add 方法。 Reference

        5
  •  1
  •   Bishoy Hanna    7 年前

    它的工作方式就是从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);
    });
    

        6
  •  0
  •   coders    7 年前

    试试这个Swift 4时间戳(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!")
    }
    }
    
        7
  •  0
  •   Stephane Paquet    6 年前

    银行代码5.1

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