0

How can i do this? I have a data stucture for each user in a user collection, I have created my own schema for the user object stored in the collection.

I want to have a favoriteMovies collection initalised into this object so that i can add movie objects inside.

Heres an example of what im trying to do :


      async function signUp(email, password){
        const {user} = await auth.createUserWithEmailAndPassword(email, password)
        
        // initialise the schema for the data
        const userInitialised = await db.collection('users').doc(user.uid).set(userSchemaObject(user.uid))
        return userInitialised;
    
        
      }

Then the schema so far:


    export default function userSchemaObject(uuid){
      return {
        uuid,
        favmovies:[]
      }
    }

2
  • What exactly is your problem? It is not clear to me. Can you give more details on what does not work as expected? Note that you cannot create an “empty collection”. A collection is created with the first document. I suspect that you mix up collection and field of type array. Again, can you give more details on the expected result and what does not work. Commented Dec 24, 2020 at 9:13
  • 1
    In other words im asking how to push data to a nested array Commented Dec 24, 2020 at 10:06

1 Answer 1

2

I'm asking how to push data to a nested array

From your question and comment, your favmovies field should be of type Array and does not seem to be "nested". Therefore you should simply use arrayUnion() in order to push data to this Array.

The following code demonstrates how to create a doc with an empty Array field, then, later, how to push a value.

const db = firebase.firestore();

const newDocRef = db.collection('test').doc();

newDocRef
    .set({
      uuid: 'uuid_value',
      favmovies: [],
    })
    .then(() => {
      newDocRef.update({
        favmovies: firebase.firestore.FieldValue.arrayUnion('movie1'),
      });
    }); 

Note that you can pass several elements to the arrayUnion() method.

newDocRef.update({
    favmovies: firebase.firestore.FieldValue.arrayUnion(
      'movie1',
      'movie2'
    ),
});
Sign up to request clarification or add additional context in comments.

2 Comments

What about pushing objects?
Pushing objects into the array or adding new elements to a map (i.e. a set of key value pairs)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.