Reputation: 23
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
});
},
Upvotes: 0
Views: 119
Reputation: 18612
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']
Upvotes: 1