首页 > 解决方案 > 是否可以在firestore中设置数组限制?

问题描述

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

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

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

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


此云功能(可在此处找到: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。


推荐阅读