【问题标题】:Is it possible to set limit for array in firestore?是否可以在firestore中设置数组限制?
【发布时间】:2021-05-13 09:49:36
【问题描述】:

我打算像这样在 Firestore 中创建一个最多只有 5 个元素的数组 数组 a = [1,2,3,4,5]

然后添加元素 6,它看起来像这样

数组 a = [2,3,4,5,6]

【问题讨论】:

  • Javasricpt 和 react native
  • 您可以尝试使用触发功能。它将工作您的阵列。如果您打算将数组从前端推送到 Firestore,那么您可以将逻辑放在那里。
  • 我认为它会像 arrayunion 自动执行,即重复将删除,如果不重复将添加,自动化

标签: javascript firebase react-native google-cloud-firestore


【解决方案1】:

此云功能(可在此处找到:https://github.com/firebase/functions-samples/blob/master/limit-children/functions/index.js)在实时数据库中满足您的需求:

'use strict';

const functions = require('firebase-functions');

// Max number of lines of the chat history.
const MAX_LOG_COUNT = 5;

// Removes siblings of the node that element that triggered the function if there are more than MAX_LOG_COUNT.
// In this example we'll keep the max number of chat message history to MAX_LOG_COUNT.
exports.truncate = functions.database.ref('/chat').onWrite((change) => {
  const parentRef = change.after.ref;
  const snapshot = change.after

  if (snapshot.numChildren() >= MAX_LOG_COUNT) {
    let childCount = 0;
    const updates = {};
    snapshot.forEach((child) => {
      if (++childCount <= snapshot.numChildren() - MAX_LOG_COUNT) {
        updates[child.key] = null;
      }
    });
    // Update the parent. This effectively removes the extra children.
    return parentRef.update(updates);
  }
  return null;
});

我相信您可以将其改编为 Firestore。

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多