0

i would like to add the 'events' id in the current user collection in my database, i achieve to get and push the Id of the user to the events collection but i don't achieve to puts multiple events Id in the user collection. I would like to know how to push events id to the user collection, each time the user create a new event, the event is pushed in an array ? My code look like that :

async createEvent() {
        await db
          .collection("events")
          .add({
            //some stuff
          })
          .then(function (docRef) {
            let lastID = docRef.id;
            let authRes = firebase.auth().currentUser;
            db.collection("users")
              .doc(authRes.uid)
              .update({ event: lastID }); //the problem is there, i would like to push the
                                            last event Id and update the user collection
          });
    },

1 Answer 1

1

There is a handy method called FieldValue.arrayUnion, which will take your value, and add it to an array if the value does not exist.

You can use it like this:

db.collection("users")
              .doc(authRes.uid)
              .set({ event: firebase.firestore.FieldValue.arrayUnion(lastID) }, {merge: true});

Note that if you do this, event will be an array of strings like this:

['eventId1', 'eventId2', 'eventId3']
Sign up to request clarification or add additional context in comments.

Comments

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.