0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

firestoreのコレクション内データをtimestampでソートする

Last updated at Posted at 2022-01-31

#具体例
消費期限前の果物をbeforeTodayFruitsList
消費期限後の果物をafterTodayFruitsList
にふり分ける(そんな運用はしないだろうけど…)。

#方法1:firestoreの複合インデックスを使用する
firestoreのインデックスタブ、複合インデックスを作成し、item_idとstarted_idをAscendingで登録したのち、以下記述する。
https://firebase.google.com/docs/firestore/query-data/index-overview?hl=ja#single-field-indexes

firebase
  .firestore()
  .collection('fruits')
  .where('item_id', '==', registor.docs[0].get('item_id').trim())
  //日付が若い順にソート
  .orderBy('expiration_date', 'asc')
  .onSnapshot(fruitsList => {
    // 本日と比較して未来と過去に分け、昇順で表示させる
    this.beforeTodayFruitsList = []
    this.afterTodayFruitsList = []
    fruitsList.forEach(value => {
      if (
        this.isBefore(value.get('expiration_date').toDate())
      ) {
        this.beforeTodayFruitsList.push(value)
      } else if (
        !(this.isBefore(value.get('expiration_date').toDate()))
      ) {
        this.afterTodayFruitsList.push(value)
      }
    })

#方法2:sort()を使用する
this.beforeTodayFruitsListは昇順
this.afterTodayFruitsListは降順
にそれぞれソートしたい場合は複合インデックスで事足りないので以下。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://stackoverflow.com/questions/7555025/fastest-way-to-sort-an-array-by-timestamp

firebase
  .firestore()
  .collection('fruits')
  .where('item_id', '==', registor.docs[0].get('item_id').trim())
  .onSnapshot(fruitsList => {
    // 本日と比較して未来と過去に分け、未来は昇順、過去は降順に表示させる
    this.beforeTodayFruitsList = []
    this.afterTodayFruitsList = []
    fruitsList.forEach(value => {
      if (
        this.isBefore(value.get('expiration_date').toDate())
      ) {
        this.beforeTodayFruitsList.push(value)
      } else if (
        !(this.isBefore(value.get('expiration_date').toDate()))
      ) {
        this.afterTodayFruitsList.push(value)
      }
    })
    this.beforeTodayFruitsList.sort(function (a, b) {
      return a.get('expiration_date') - b.get('expiration_date')
    })
    this.afterTodayFruitsList.sort(function (a, b) {
      return b.get('expiration_date') - a.get('expiration_date')
    })
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?