1

I am trying to remove an object from array in in firestore, but encountered an obstacle what are the requirement or the reference to do the removal ? does one key value in the object sufficient to do the remove or should the object by identical to the one that is getting removed ?

const deleteWeek = async () => {
        const docRef = doc(db, 'Weeks', id);
        await updateDoc(docRef, {
          weeks: arrayRemove({
            weekId: '7518005f-7b10-44b6-8e0a-5e41081ee064',
          }),
        });
      };
      deleteWeek();
    }

however week in data base looks like this

{name ,"Week 2"
days : [/*data all kinds*/]
weekId : "7518005f-7b10-44b6-8e0a-5e41081ee064"}

2 Answers 2

3

If it's an array of object, then you need to know the whole object to use arrayRemove() For example, if the a document looks like this:

{
  ...data
  weeks: [
    { 
      name: "Week 2",
      days: [/*data all kinds*/]
      weekId: "7518005f-7b10-44b6-8e0a-5e41081ee064"}
    }
  ]
}

You'll have to pass the entire week object in arrayRemove(). It might be better to store such data in sub-collections instead so you can query/delete a specific one.

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

3 Comments

including sub items ? like the data in the days array ?
@Richardson yes.
@Richardson ofc with the data included !! otherwise it won't work !! are you new to firebase ??
0

Since there is no function in firestore to delete only a element in array, you need to make arrayRemove refer to the same object you want to delete, then create a new object and insert it with arrayUnion method

in my case, i use to below

 const { leave,date,email } = req.body;

  const attendanceRef = admin.firestore().collection('Attendance').doc(`${email}`);
  
  const attendanceData = await attendanceRef.get();

  const attendanceRecord = attendanceData.data().attendance;

  const removeTarget = attendanceRecord.find((item) => item.date === date);

  await attendanceRef.update({
    attendance: admin.firestore.FieldValue.arrayRemove(removeTarget),
  })

  const obj = {
    ...removeTarget,
    "leave": leave,
  }

  await attendanceRef.set({
    attendance: admin.firestore.FieldValue.arrayUnion(obj),
  },{ merge: true })
  const newAttendance = await attendanceRef.get();
  const newAttendanceRecord = newAttendance.data().attendance;

  return await res.json({
    message: '퇴근시간이 저장되었습니다.',
    attendance:newAttendanceRecord
  });

after update, it maybe if error occured. if error occured, you need all working cancel. this case, you may want to use batch method

const admin = require('firebase-admin');


module.exports = async function(req,res) {
  const { leave,date,email } = req.body;

  const batch = admin.firestore().batch();

  const attendanceRef = admin.firestore().collection('Attendance').doc(`${email}`);
  
  const attendanceData = await attendanceRef.get();

  const attendanceRecord = attendanceData.data().attendance;

  const removeTarget = attendanceRecord.find((item) => item.date === date);

  // await attendanceRef.update({
  //   attendance: admin.firestore.FieldValue.arrayRemove(removeTarget),
  // })
  batch.update(
    attendanceRef,{ attendance: admin.firestore.FieldValue.arrayRemove(removeTarget) }
  )

  const obj = {
    ...removeTarget,
    "leave": leave,
  }
  
  // await attendanceRef.set({
  //   attendance: admin.firestore.FieldValue.arrayUnion(obj),
  // },{ merge: true })
  batch.set(
    attendanceRef, { attendance: admin.firestore.FieldValue.arrayUnion(obj) },{ merge: true }
  )


  await batch.commit();

  const newAttendance = await attendanceRef.get();
  const newAttendanceRecord = newAttendance.data().attendance;
  return await res.json({message: '퇴근시간이 저장되었습니다.',attendance:newAttendanceRecord});
}

hope help this for you

Comments

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.