Add timestamp in Firestore documents

前端 未结 10 1007
旧巷少年郎
旧巷少年郎 2020-12-29 03:29

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

Important: Unlike \"push IDs\" in the Firebase Realtime Database, Cloud Firestore au

相关标签:
10条回答
  • 2020-12-29 04:04

    This solution worked for me:

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

    The result in Cloud Firestore is: Cloud Firestore Result

    0 讨论(0)
  • 2020-12-29 04:04

    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);
    });
    

    });

    0 讨论(0)
  • 2020-12-29 04:09

    Swift 5.1

    ...
    "dateExample": Timestamp(date: Date()),
    ...
    
    0 讨论(0)
  • 2020-12-29 04:11

    I am using Firestore to store data that comes from a Raspberry PI with Python. The pipeline is like this:

    Raspberry PI (Python using paho-mqtt) -> Google Cloud IoT -> Google Cloud Pub/Sub -> Firebase Functions -> Firestore.

    Data in the device is a Python Dictionary. I convert that to JSON. The problem I had was that paho-mqtt will only send (publish) data as String and one of the fields of my data is timestamp. This timestamp is saved from the device because it accurately says when the measurement was taken regardless on when the data is ultimately stored in the database.

    When I send my JSON structure, Firestore will store my field 'timestamp' as String. This is not convenient. So here is the solution.

    I do a conversion in the Cloud Function that is triggered by the Pub/Sub to write into Firestore using Moment library to convert.

    Note: I am getting the timestamp in python with:

    currenttime = datetime.datetime.utcnow()

    var moment = require('moment'); // require Moment 
    function toTimestamp(strDate){
      return parsedTime = moment(strDate, "YYYY-MM-DD HH:mm:ss:SS");
     }
    
    exports.myFunctionPubSub = functions.pubsub.topic('my-topic-name').onPublish((message, context) => {
    
      let parsedMessage = null;
      try {
        parsedMessage = message.json;
    
        // Convert timestamp string to timestamp object
        parsedMessage.date = toTimestamp(parsedMessage.date);
    
        // Get the Device ID from the message. Useful when you have multiple IoT devices
        deviceID = parsedMessage._deviceID;
    
        let addDoc = db.collection('MyDevices')
                        .doc(deviceID)
                        .collection('DeviceData')
                        .add(parsedMessage)
                        .then ( (ref) => {
                          console.log('Added document ID: ', ref.id);
                          return null;
                        }).catch ( (error) => {
                          console.error('Failed to write database', error);
                          return null;
                        });
    
      } catch (e) {
        console.error('PubSub message was not JSON', e);
      } 
    
      // // Expected return or a warning will be triggered in the Firebase Function logs.
      return null;  
    });
    
    0 讨论(0)
  • 2020-12-29 04:12

    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.)
    0 讨论(0)
  • 2020-12-29 04:20
    firebase.firestore.FieldValue.serverTimestamp()
    

    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 
    })
    
    0 讨论(0)
提交回复
热议问题