Robel Eyzsu
Robel Eyzsu

Reputation: 29

unable to append objects in firebase document

 var single_Catagory = [
        {
          name: title,
          price: price,
          scrachedPrice: scrachedPrice,
          color: colors,
          sizeList: sizes,
          stockStatusAvailablity: inStockAvailablity,
          productInStock: productInStock,
          rating: rating,
          productDescription: productDescription,
        },
      ];

      db.collection("catagory")
        .doc("catagories")
        .set({ electronics: single_Catagory })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });

this is my code for writing in my firebase firesore collection "catagroy" and it has one document "catagories",when I inserted one object I can't append other objects in firestore document. please I got stuck ..help me

Upvotes: 0

Views: 186

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

In addition to Dobromir's answer on how to add another field to the document, here's how you can add another item to the electronics array in your existing document:

var second_Catagory = {
  name: "second name",
  price: price,
  scrachedPrice: scrachedPrice,
  color: colors,
  sizeList: sizes,
  stockStatusAvailablity: inStockAvailablity,
  productInStock: productInStock,
  rating: rating,
  productDescription: productDescription,
},

db.collection("catagory")
  .doc("catagories")
  .update({ electronics: firebase.firestore.FieldValue.arrayUnion(second_Catagory) })

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

Upvotes: 1

Dobromir Kirov
Dobromir Kirov

Reputation: 1033

How to add documents to firestore collection? And how to modify them?

// Add a new document in collection "cities"
db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})
.then(() => {
    console.log("Document successfully written!");
})
.catch((error) => {
    console.error("Error writing document: ", error);
});

And if this document is not existing one its going to be created, but if its already there the data will be overwriten by the latest document.
Of course there is a option that can prevent that from happening.

var cityRef = db.collection('cities').doc('BJ');

var setWithMerge = cityRef.set({
    capital: true
}, { merge: true });

This explanation is very basic but usefull for further understanding of how firebase is working. All of it is from the firebase docs, they are very well made take a look at them.

https://firebase.google.com/docs/firestore/manage-data/add-data#web-version-8

Upvotes: 1

Related Questions