Home > Net >  How to update field in firebase document?
How to update field in firebase document?

Time:11-06

Hello I want to update a field in a firebase document.

Right now , I am accessing the document collection like this However I am having trouble setting teh shares field of the doc to shares =1 ? What am i doing wrong here in the set method?

const buyStock = async () => {
const q = await query(
  collection(db, 'myStocks'),
  where('ticker', '==', props.name)
);
const querySnapshot = await getDocs(q);
if (!querySnapshot.empty) {
  // simply update the record

  querySnapshot.forEach((doc) => {
    doc.id.set({
      shares: doc.id.data().shares =1
    })
    // doc.data() is never undefined for query doc snapshots
    console.log(doc, doc.id, ' => ', doc.data());
  });

CodePudding user response:

You're almost there. To update a document, you need a reference to that document. You can get this with:

querySnapshot.forEach((doc) => {
  doc.ref.update({
    shares: doc.data().shares =1
  })
});

You can also use the built-in atomic increment operator:

doc.ref.update({
  shares: increment(1)
})

CodePudding user response:

It looks like you are calling the set method on the 'id' field. Try to remove that. So just do

doc.set({
  shares: doc.data().shares =1
})

give that a shot. If that doesn't work, i'd try updating a document that is not part of a query snapshot.

  • Related