[英]add objects to array without overwriting
I have my current code我有我当前的代码
let array = {};
array[date] = [
{
Name: Name,
Cell: Cell,
Age: Age,
userId: userId,
Time: time,
Type: type,
read: false,
},
];
that uploads to firebase like this像这样上传到 firebase
but every time i add a new entry for the same date, it overwrites the existing data.但是每次我为同一日期添加一个新条目时,它都会覆盖现有数据。 I want the data to be add to map "1" etc instead of overwriting the data in map "0"
我希望将数据添加到 map "1" 等,而不是覆盖 map "0" 中的数据
update: I have tried the following and I am receiving an error.更新:我尝试了以下方法,但收到错误消息。 Not sure if I did this correctly, I am still learning.
不知道我是否正确地做到了这一点,我仍在学习。
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);
}
update with 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);
}
},
Solution:解决方案:
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, }), });尝试 { 等待 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); } 捕捉 (e) { 警报(e); console.log(e);
控制台.log(e); }
}
Since you set the entire 2022-01-03
field, you are overwriting any existing values in that field.由于您设置了整个
2022-01-03
字段,因此您将覆盖该字段中的任何现有值。
If you want to merge the new value/object you specify with the existing values in a field use the array-union
operator .如果要将指定的新值/对象与字段中的现有值合并,请使用
array-union
运算符。
Use push()
to add to an array.使用
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,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.