0

My current logic is the following creating adding a document with a user id in to users collection, and push the first object, then on the second call I want to be able to update the excising array with a new object.

const docRef = doc(db, 'user', _authContext.currentUser.uid);
const payload = { items: [{item1 : 1}] };
await setDoc(docRef, payload);


// New array after update (second call of the function)
items: [{item1 : 1}, {item2 : 2}]

1 Answer 1

1

I think you're looking for:

await updateDoc(docRef, { items: arrayUnion({ item2: 2 }) });

Also see the Firebase documentation on adding items to an array.

Sign up to request clarification or add additional context in comments.

3 Comments

would it work ,if the doc is not there to begin with ?
I want to be able to create on the fly since the array will be dependent on a user, and I could have 1000 , for example, since I don't have access to the document id before creating the document and I want to related to users form authentication
If the doc may not exist yet, you'll need to use setDoc and provide merge options.

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.