Reputation: 125
I am trying to push an object into an array that is stored to the user in firebase. I have this. It starts on click
function savetodb() {
auth.onAuthStateChanged(user => {
if(user) {
db.collection('users').doc(user.uid).get().then(doc => {
const saveditems1 = doc.data().saveditems
saveditems1.push({
Name:'Test',
Price:'Test',
Link:'https://www.test.com'
})
});
}
else {
return alert('no')
}
})
There is no errors in the console, but it doesn't add anything to the user's array.
Here is the on click function
<button id="savedb" onclick='savetodb()'>Save For Later</button>
I don't know why It isn't adding to the array. Here is how it is stored in firestore
Upvotes: 1
Views: 2087
Reputation: 4174
Firestore arrays don't support index'd arrays that you can push into, behind the scenes they use ordered lists and you must invoke an arrayUnion
Firestore function.
It is important to note that the document does not need to exist if you use set:merge
methods as arrayUnion
will generate the array if it does not exist.
const data = {
Name: 'Test',
Price: 'Test',
Link: 'https://www.test.com'
}
doc.set({
saveditems: firebase.firestore.FieldValue.arrayUnion(data)
},
{merge:true});
To remove items from an array, you must pass the exact value back to an arrayRemove
function.
const data = {
Name: 'Test',
Price: 'Test',
Link: 'https://www.test.com'
}
doc.update({
saveditems: firebase.firestore.FieldValue.arrayRemove(data)
});
Upvotes: 1
Reputation: 76579
.push()
isn't suitable for the task; you'd have to use firebase.firestore.FieldValue.arrayUnion
and firebase.firestore.FieldValue.arrayRemove
to perform array-manipulation in Firestore.
See https://firebase.google.com/docs/firestore/manage-data/add-data#web-v8_11.
Something alike (assuming that data-type object
is being supported):
doc.update({
saveditems: firebase.firestore.FieldValue.arrayUnion({
Name: 'Test',
Price: 'Test',
Link: 'https://www.test.com'
})
});
There's also admin.firestore.FieldValue
counterparts, but these are for NodeJS.
Upvotes: 0