Firebase Firestore“按时间排序”

时间:2019-07-23 05:28:35

标签: javascript firebase web google-cloud-firestore saga

我正在尝试实现Firebase数据库“按时间戳排序”同步,但无法解决。

对我来说,它不是按“任何顺序”保存邮件

以下是我的同步代码块:

let time =  {time: moment().format('MM Do YY, h:mm: a')}
const createMessage = (uid, text, displayName) => ({
  uid,
  text,
  displayName,
  time
})

function * syncMessagesSaga () {
    //ordering by uid does not make sense to me
    const channel = yield call(()=>prsf(({rsf})=>
     rsf.firestore.channel('messages')));
    while(true) {
        const snapshot = yield take(channel);
        let messages = [];
        snapshot.forEach(message => {
            messages.push({id: message.id, ...message.data()})  
        });
        yield put(syncMessages(messages))

      }
}

问题是我必须放置以下代码块

.orderBy("time", "asc")

但是我不知道要在哪里添加

我在想这可能是由于我的发送代码功能未按顺序保存 我发送和保存的代码块:

function * sendMessageSaga (action) {
  const rsf= yield call(getRsf);
  const uid = yield select(state => state.login.user.uid)
  const displayName = yield select(state => state.login.user.displayName)

  yield call(rsf.firestore.addDocument, 'messages', createMessage(uid, action.message, displayName))
  yield put(reset('DCTForm'))
  yield put(reset('MessageForm'))
  yield put(changeNewMessage(''))
}

1 个答案:

答案 0 :(得分:0)

因此,在进行了集思广益之后,我对问题的解决了: 我使用了具有数组排序功能的函数: 代码块:-

function compareValues(key, order = 'asc') {
      return function (a, b) {
        if (!a.hasOwnProperty(key) ||
          !b.hasOwnProperty(key)) {
          return 0;
        }
        const varA = (typeof a[key] === 'string') ?
          a[key].toUpperCase() : a[key];
        const varB = (typeof b[key] === 'string') ?
          b[key].toUpperCase() : b[key];

        let comparison = 0;
        if (varA > varB) {
          comparison = 1;
        } else if (varA < varB) {
          comparison = -1;
        }
        return (
          (order == 'desc') ?
            (comparison * -1) : comparison
        );
      };
    }
    yield put(syncMessages(messages.sort(compareValues('time'))))

让我知道正确的解决方法,直到您误用它为止 谢谢