tengo mi codigo actual
let array = {}; array[date] = [ { Name: Name, Cell: Cell, Age: Age, userId: userId, Time: time, Type: type, read: false, }, ];pero cada vez que agrego una nueva entrada para la misma fecha, sobrescribe los datos existentes. Quiero que los datos se agreguen al mapa "1", etc. en lugar de sobrescribir los datos en el mapa "0".
actualización: he intentado lo siguiente y estoy recibiendo un error. No estoy seguro si hice esto correctamente, todavía estoy aprendiendo.
let array = {}; array[date] = []; try { await firebase .firestore() .collection("Notifications") .doc(`${helper}`) .update( { array: firebase.firestore.FieldValue.arrayUnion({ Name: Name, Cell: Cell, Age: Age, userId: userId, Time: time, Type: type, read: false, }), }, { merge: true } ); } catch (e) { alert(e); console.log(e); }actualizar con push:
// at beginning of script let array = {}; // later, when you want to add to it if (!array[date]) { array[date] = []; } array[date].push({ Name: Name, Cell: Cell, Age: Age, userId: userId, Time: time, Type: type, read: false, }); try { await firebase .firestore() .collection("Notifications") .doc(`${helper}`) .set( array, { merge: true } ); } catch (e) { alert(e); console.log(e); } },Solución:
try { await firebase .firestore() .collection("Notifications") .doc(`${helper}`) .update({ [date]: firebase.firestore.FieldValue.arrayUnion({ Name: Name, Cell: Cell, Age: Age, userId: userId, Time: time, Type: type, read: false, }), }); } catch (e) { alert(e); console.log(e); }Dado que configuró todo el campo 2022-01-03 , está sobrescribiendo cualquier valor existente en ese campo.
Si desea fusionar el nuevo valor/objeto que especifica con los valores existentes en un campo, use el operador array-union .
Use push() para agregar a una matriz.
// at beginning of script let array = {}; // later, when you want to add to it if (!array[date]) { array[date] = []; } array[date].push({ Name: Name, Cell: Cell, Age: Age, userId: userId, Time: time, Type: type, read: false, });