This question already has answers here:
Include the document id as a field id in firestore
(3 answers)
Closed 7 months ago.
I'm trying to save to document ID inside a field in the same document. I'm currently doing it like this:
const myDoc = await firestore().collection("users").doc(auth().currentUser?.uid).collection("myCol").add({
test: "Hello, World!"
});
myDoc.update({id: myDoc.id})
Is it possible to do this without having to write to the database 2 times?
This is stated in this documentation, for reference, see snippet below:
const myDoc = firestore().collection("users").doc(auth().currentUser?.uid).collection("myCol").doc();
await myDoc.set({
test: "Hello, World!",
id: myDoc.id
});
This would get the document ID that you would use when adding a document. You need to use the set() method instead of add() method.
You could also use uuid to set a custom document ID when adding it in your Firestore Database.
Related
This question already has answers here:
Flutter: Update specific index in list (Firestore)
(2 answers)
How to delete/update specified index in an array object from firestore with flutter
(1 answer)
Flutter Firestore: update array of object by param
(1 answer)
Closed 9 months ago.
I have a Firebase array that looks like this
categories:[{rating: 1, name: 'abc'}, {rating: 2, name: 'xyz'}]
How can I update the element with name 'abc' for example to make it something like this
{rating: 3, name: 'abc'}
I tried the below but it adds an element to the array as it considers it unique due to the different rating value.
var ref = _db.collection('reports').doc(user.uid);
const data = { categories: FieldValue.arrayUnion([{"name": 'abc', "rating": 3}]) }
ref.set(data, SetOptions(merge: true));
You need to read the Array, modify it in your front-end and write it back to Firestore (i.e. update the document by passing the entire modified array).
This question already has answers here:
flutter firestore, add new object in array
(4 answers)
how to add or remove item to the the existing array in firestore ?
(2 answers)
Firestore: add or remove elements to existing array with Flutter [duplicate]
(1 answer)
Closed 1 year ago.
I want to add a new field in a array but when i try to add a new field it will remove rest and add only the remaining one.
i tried this but not working
collectionRef
.doc("userIdLalit")
.collection("stories")
.doc("BHUCC3ewEeByJ6U68ygJ")
.update(
{
"reactionModel": {
"user": [
{"fourth element": "Sam"},
],
}
},
);
This code will remove the 0th and 1st element and add the fourth element but i want all of them whenever i add a new field
I tried with set method with merge true but didnt work
You can use FieldValue.arrayUnion() to push a new item to the array:
collectionRef
.doc("userIdLalit")
.collection("stories")
.doc("BHUCC3ewEeByJ6U68ygJ")
.update({
"reactionModel.user": FieldValue.arrayUnion({"fourth element": "Sam"})
});
Also the array is nested in a map so you would have to use dot notation to update it i.e. "reactionModel.user".
This question already has answers here:
Delete a Document with all Subcollections and Nested Subcollections in Firestore
(13 answers)
Closed 2 years ago.
The Document I am trying to Delete
I want to delete a document which is further having collections inside it. I am running this code
db.collection("users").document(uid)
.delete()
.addOnCompleteListener {
if (it.isSuccessful) {
Log.i("logcat", "Success")
} else {
Log.i("logcat", "Fail")
}
}
The output in Logcat is Success still I see the document present on the console. However when i mention the complete reference(db.collection("users").document("uid).collection("amount")........), individual documents inside it gets deleted but I need to delete the document with all its collections inside. Am I trying it the wrong way or some limitation of Firebase?
Welcome to Stackoverflow!
In this case to delete subcollections you need to read this:
https://firebase.google.com/docs/firestore/solutions/delete-collections
Basically you will need to use a recursive delete like this:
await firebase_tools.firestore
.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
yes: true,
token: functions.config().fb.token
});
This question already has answers here:
Flutter Firestore Server side Timestamp
(4 answers)
Closed 2 years ago.
I am writing code to set data to Firestore from flutter. What I want is to add a field for the time the data is created, eg "createdOn". DateTime.now() for Flutter takes the time from the device but I would like to get the serverside time. My code is as below:
Future updateDataModel(String userName, String userPosition, String userLocation) async{
return await userCollection.document().setData({
'userName' : userName,
'userPosition' : userPosition,
'userLocation' : userLocation
});
}
It would be a great help if I could have a field like below that gets the timestamp for firebase.
'createdOn' : TimestampHere,
You can use the FieldValue.serverTimestamp()
serverTimestamp(): FieldValue Returns a sentinel used with set() or
update() to include a server-generated timestamp in the written data.
'createdOn':FieldValue.serverTimestamp()
References
ServerTimestamp
you can use several types of time stamp ,example date time
"timestamp": DateTime.now(),
server value
'timestamp' : Timestamp.now()
If you are using Firebase,you should store the timestamp from epoch like that
DateTime.now().microsecondsSinceEpoch
I'm trying to get the id/key of added item after adding processing
for example, this is my add function
add(){
let todayTime = moment().format('YYYY-MM-DD, HH:mm')
this.afd.list('/questions/').push({
uemail: this.userService.email,
title: this.variables.title,
text: this.variables.text,
type: this.variables.type
})
}
So how can I get the id directly (when item added successfully) ?
According to firebase doc
let key = this.afd.list('/questions/').push().key;
You get the key before pushing your data. It is useful when you need simultaneously add data in different locations using .update()