Is it possible to set limit for array in firestore?

i am planning to create an array of only 5 elements max in firestore like this Array a = [1,2,3,4,5]

then add element 6 it will look like this

Array a = [2,3,4,5,6]

Upvotes: 0

Views: 94

Answers (1)

Ken
Ken

Reputation: 212

This cloud function (found here: https://github.com/firebase/functions-samples/blob/master/limit-children/functions/index.js) does what you want in Realtime Database:

'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;
});

I believe you can adapt it for Firestore.

Upvotes: 2

Related Questions