【问题标题】:Firebase functions shuffle firestore array onUpdateFirebase 函数 shuffle firestore 数组 onUpdate
【发布时间】:2025-11-26 18:20:04
【问题描述】:

我想获得充满多张地图的Question Array。 这是我的 Firebase 结构:Firebase structure 然后我想用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 functionFunction execution took 22 ms, finished with status: 'error'

我做错了什么?

【问题讨论】:

  • 您的 questionsArr 似乎是一个对象数组。我认为 js 数组没有可用的“更新”方法。我认为您将该数组视为 Firestore 文档引用?

标签: node.js firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

update 方法是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) });
    });

【讨论】:

  • 完美运行。我唯一需要调整的是回报:return snap.ref.update({ questions: shuffle(questionsArr) });
  • 嘿@kartse,你也可以upvote the answer。谢谢。