Ad

"userIDs.push Is Not A Function" When Trying To Push A New Variable To An Array

- 1 answer

I am having high difficulity understanding what am I doing wrong. I am coming from Android world where everything is so much simplier...anyway, I have a function that checks if the firebase database table I want to update exist, if not it creates one. So far so good, the issue is that after creating the table I want to update it's content afterwards and I am having issues understanding why I can't update the array I created.

here is my code -

enter image description here

as I sayed, I am having problems to push to my array. At firebase console log I get the following error -

enter image description here

As far as I know, arrays have the '.push' method. So what is it that I am doing wrong?

edit -

Here is how my database looks like. Obviously, I am holding 2 variables and not a variable and a list as I would like to. I want userUIDs to be a list -

enter image description here

edit -

here is my code -


function createOrUpdateDeletedVideosTable(profileUid, response) {

    const deletedVideosRef = database.ref(config.ENTITY_NAME_DELETED_VIDEOS);
    return deletedVideosRef.once("value").then(deletedVideosSnapshot => {
        var snapshotValue = JSON.stringify(deletedVideosSnapshot);
        console.log("snapshot value is null - " +  snapshotValue !== "null")
        console.log("snapshot value is null - " +  snapshotValue !== null)
        if (snapshotValue !== "null") {
            console.log("deleted videos ref exists - " + JSON.stringify(deletedVideosSnapshot));
            var deletedVideosVar = deletedVideosSnapshot.val();
            console.log(JSON.stringify(deletedVideosVar))
            deletedVideosVar["totalVideosDeleted"] = deletedVideosVar.totalVideosDeleted += 1
            deletedVideosVar.userUIDs.push(profileUid);
            deletedVideosRef.set(deletedVideosVar);
            return response.status(200).send('{"result": "OK"}');
        } 
        console.log("deleted videos ref does not exist")
        return createDeletedVideosTable(profileUid, response);
    }).catch(err => {
        console.log(err);
        return response.status(500).send(`deleted video counter error - ${err}`);
    });
 }

 function createDeletedVideosTable(profileId, response) {
    var deletedVideosVar = {
        totalVideosDeleted : 1,
        userUIDs : {
            profileId
        }
    };
    // deletedVideosVar.totalVideosDeleted  = 1
    // deletedVideosVar.userUIDs.push(profileId);
    database.ref(config.ENTITY_NAME_DELETED_VIDEOS).set(deletedVideosVar);
    return response.status(200).send('{"result": "OK"}');
 }


Ad

Answer

This is most probably because deletedVideosVar["usersUIDs"] is not an array.

By doing deletedVideosVar["usersUIDs"] you are accessing the usersUIDs property of the deletedVideosVar object, using the square brackets notation, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

As explained in the Realtime Database doc, "depending on the data in a DataSnapshot, the val() method may return a scalar type (string, number, or boolean), an array, or an object".

If you share the structure of your database we might confirm the assumption that deletedVideosVar["usersUIDs"] is not an array.


UPDATE following your comment:

The following code will update a Realtime Database node that is an array with new values. Note that, with the Realtime Database, you need to first read the existing array, then push a value and re-write the entire array.

  var db = firebase.database();
  var myRef = db.ref('myRef');

  myRef.once('value').then(function(snapshot) {
    //Let's create a random value for this example
    var random = Math.floor(Math.random() * 500 + 1);

    if (snapshot.exists()) {

      var newArray = snapshot.val().array;
      newArray.push('A' + random);

      var postData = {
        array: newArray
      };

      var updates = {};
      updates['myRef'] = postData;
      db.ref().update(updates);
    } else {
      var postData = {
        array: ['A' + random]
      };

      myRef.set(postData);
    }
  });

For the increment of deletedVideosVar.totalVideosDeleted, you should probably use a transaction, see https://firebase.google.com/docs/database/web/read-and-write?authuser=0#save_data_as_transactions

Ad
source: stackoverflow.com
Ad