[英]Flutter Firestore create new Array every time function called
As per the question I'd like to add a new array every time I call my addPredection function for example I'd like it to look like this.根据这个问题,我想在每次调用 addPredection function 时添加一个新数组,例如,我希望它看起来像这样。
Currently its just updating the current value everytime目前它只是每次更新当前值
My code is as follows:我的代码如下:
///add prediction function
Future<String?> addPrediction() async {
var currentUser = FirebaseAuth.instance.currentUser;
var todaysDate = DateTime.now().toString();
var doesExist = await FirebaseFirestore.instance
.collection('collection')
.doc(currentUser!.uid)
.get();
if (doesExist.exists == true) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.update({
'Predictions':
FieldValue.arrayUnion([todaysDate,'angry', 'Happy'])
});
}
if (doesExist.exists == false) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.set({
todaysDate: FieldValue.arrayUnion(['angry', 'Happy'])
}, SetOptions(merge: false));
}
For adding items you also have to apply the SetOptions but with the merge set to true, like this:要添加项目,您还必须应用SetOptions ,但将合并设置为 true,如下所示:
var todaysDate = DateTime.now().toString();
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.UID).set({
todaysDate : ['angry', 'happy']
}, SetOptions(merge: true));
I did it on my end and I believe they come out the way you want:我是自己做的,我相信它们会按照您想要的方式出现:
The merge: true on the SetOptions what it does is that it appends to the existing document. SetOptions上的merge: true它所做的是附加到现有文档。 The set method by default overrides the existing fields unless the merge: true option is there.
默认情况下, set方法会覆盖现有字段,除非存在merge: true选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.