首页 > 解决方案 > Firebase 函数 shuffle firestore 数组 onUpdate

问题描述

我想得到Question Array其中充满了多张地图。这是我的 Firebase 结构:Firebase 结构 然后我想用shuffle函数对其进行洗牌,然后在我的 Firestore 中更新它。

 exports.shuffleSet = functions.firestore
.document('duell/{duell_id}')
.onCreate((snap, context) => {
  
  const data = snap.data();
  const questionsArr = data.set.question;
  console.log(questionsArr);

  const shuffle = (array) => {
    var currentIndex = array.length,  randomIndex;
  
    while (0 !== currentIndex) {

      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;

      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex], array[currentIndex]];
    }
    console.log("Geshuffled: " + array);
    return array;
  }

  return questionsArr.update(shuffle(questionsArr));
});

我总是在我的日志中得到TypeError: questionsArr.update is not a function和。Function execution took 22 ms, finished with status: 'error'

我做错了什么?

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


更新方法是DocumentReference类的方法。所以你必须snap.ref按如下方式调用它:

exports.shuffleSet = functions.firestore
    .document('duell/{duell_id}')
    .onCreate((snap, context) => {

        const data = snap.data();
        const questionsArr = data.set.question;
        console.log(questionsArr);

        const shuffle = (array) => {
            var currentIndex = array.length, randomIndex;

            while (0 !== currentIndex) {

                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex--;

                [array[currentIndex], array[randomIndex]] = [
                    array[randomIndex], array[currentIndex]];
            }
            console.log("Geshuffled: " + array);
            return array;
        }

        return snap.ref.update({ shuffle: shuffle(questionsArr) });
    });

推荐阅读