Firebase cloud function firestore array union

依然范特西╮ 提交于 2019-12-24 08:03:04

问题


I'm unable to get the array union or increment to work properly in firebase cloud functions.

return docRef.update({

  object: {
    count: admin.firestore.FieldValue.increment(1),
    list: admin.firestore.FieldValue.arrayUnion({
      space_id: newData.date_id,
      user: {
        displayName: "john doe"
      }
    })
  }

When the function runs, it simply overwrites the existing data in the list array and the count is always set to 1 even though it currently exists and is of number type.


回答1:


Following you comment, here is below the HTML code I tried. Note that it is not Cloud Function code (which uses the Admin SDK) but some JavaScript code using the JavaScript SDK. But most probably the Admin SDK has the same behavior.

To try it do as follows:

  1. Create a collection testSO in Firestore and a doc with ID doc1 and one dummy field.
  2. Save this HTML page on your computer and open it in browser.
  3. Then change the values and reload the page in the browser for experimenting the behavior

You will see that both arrayUnion and increment work when used with an array of strings for arrayUnion (field array1) and a number for increment (field count1) but not with the compounded object.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>

    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-functions.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-firestore.js"></script>
      </head>

  <body>
    <script>
      // Initialize Firebase
      var config = {
        apiKey: 'xxxxxxxxxxx',
        authDomain: 'xxxxxxxxxxx',
        databaseURL: 'xxxxxxxxxxx',
        projectId: 'xxxxxxxxxxx'
      };

      firebase.initializeApp(config);

      var db = firebase.firestore();

      db.doc('testSO/doc1').update({
        count1: firebase.firestore.FieldValue.increment(1),
        array1: firebase.firestore.FieldValue.arrayUnion('arrayItem'),
        object: {
          count: firebase.firestore.FieldValue.increment(1),
          list: firebase.firestore.FieldValue.arrayUnion({
            space_id: 'spaceNbr',
            user: {
              displayName: 'john doe'
            }
          })
        }
      });
    </script>
  </body>
</html>


来源:https://stackoverflow.com/questions/55559553/firebase-cloud-function-firestore-array-union

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!