Add timestamp in Firestore documents

前端 未结 10 1011
旧巷少年郎
旧巷少年郎 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: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;  
    });
    

提交回复
热议问题