How to sort firestore documents by '_createTime'?
Asked Answered
P

1

6

I'm using a cloud Firebase function with Admin SDK to fetch the most recent document from my Firestore collection. Ordering is based on a timestamp field. This value is explicitly provided when the document is written.

Fetching code:

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())

The console.log statements print the below output. Look at _createTime in the bottom.

Output:

QueryDocumentSnapshot {
  _fieldsProto: {
    coinsToday: { doubleValue: 0.017, valueType: 'doubleValue' },
    timestamp: { timestampValue: [Object], valueType: 'timestampValue' }
  },
  _ref: DocumentReference {
    _firestore: Firestore {
      _settings: [Object],
      _settingsFrozen: true,
      _serializer: [Serializer],
      _projectId: 'hidden',
      registeredListenersCount: 0,
      _lastSuccessfulRequest: 1596692513232,
      _backoffSettings: [Object],
      _preferTransactions: false,
      _clientPool: [ClientPool]
    },
    _path: QualifiedResourcePath {
      segments: [Array],
      projectId: 'hidden',
      databaseId: '(default)'
    },
    _converter: {
      toFirestore: [Function: toFirestore],
      fromFirestore: [Function: fromFirestore]
    }
  },
  _serializer: Serializer {
    createReference: [Function (anonymous)],
    allowUndefined: false
  },
  _readTime: Timestamp { _seconds: 1596692513, _nanoseconds: 164886000 },
  _createTime: Timestamp { _seconds: 1596692167, _nanoseconds: 68734000 },
  _updateTime: Timestamp { _seconds: 1596692167, _nanoseconds: 68734000 }
}

Transaction created at 2020-08-06T05:36:07.069Z

I'm looking for a way to order documents by _createTime instead of writing a timestamp value every time. Using orderBy('_createTime') or orderBy('createTime') has not worked.

Pence answered 6/8, 2020 at 5:54 Comment(0)
Z
7

Using a field as you are currently doing, is the correct way. You cannot order on the metadata ',_createTime'. According to https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document: "If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents."

Zoology answered 6/8, 2020 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.