How to delete specific field in firebase firestore (flutter) - firebase

I trying to delete specific field in firebase firestore uisng flutter if the user enter one of the serial code is this collection.
Here is my collection for example if the user enter rhdrVjVxcnCCj55c Serial 1 should be empty.
collection and fields
I treid this but dose not work
CollectionReference sCodes = FirebaseFirestore.instance
.collection('Register New System ( serial code )');
sCodes
.doc('Serial Codes')
.update({_serialCodeController.text: FieldValue.delete()})
.then((value) => print("User's Property Deleted"))
.catchError(
(error) => print("Failed to delete user's property: $error"));

Related

Flutter Firestore update document name inside of collection

I am trying to add the ability to update the document name inside of my usernames collection inside my Flutter app. Here is my upload function:
Future<void> updateUsername() {
// Add a new user inside our the Usernames Collection. This is useful to check for username availablilty.
return usernames
.doc(username)
.set({
'uid': uid,
'timeCreated': DateTime.now(),
})
.then((value) => print("Username Added"))
.catchError((error) => print("Failed to add username: $error"));
}
Here is my database setup:
There is no option in firestore to rename a document. The way the most uses is to create a new document with the new name and the data that been in the old document, then delete the old document.
Take a look here: Can I change the name of a document in Firestore?
One more advice, if you're not going to put any data in the usernames documents, then make a document that has the name "usernames" and add them there, that would help to make less reads ... unless you know what you're doing.

How to change the value of array field in firebase flutter?

I have an array containing list of image URL in firestore. I want to delete the specific image of certain index when user clicks the delete button. This is how my firebase image array looks like Here's what i've tried
FirebaseFirestore
.instance
.collection(
'adsPost')
.doc(widget.id)
.update({
'${images[_current]}':
''
}).whenComplete(() {
print(
'image removed from firestore');
});
You have two options, to remove it from the list in your app, and then update your firebase document with the new modified listed after the image was deleted.:
.update({"images": images.remove(images[_current])});
Or delete it from Firebase:
.update({"images": FieldValue.arrayRemove([images[_current]])})

Firestore/Cloud functions: Finding a document in array of document references that match criteria

Using Firebase Cloud Functions I'd like to search for documents that contain a certain other document in an array of document references. My structure looks as follows;
Users
name
email
cars
ref to cars/car1 for example
ref to cars/car2 for example
Cars
registration
make
model
There are multiple users and multiple cars. I need to search for users that have a certain 'car' in their car array.
I'm trying to write this in a Cloud Function and have the following;
admin.firestore()
.collection('users')
.where('cars', 'array-contains', registration)
.get().then(doc => {
console.log("TESTING: found the user " + doc.data().email)
return
}).catch(error => {
console.error(error);
});
I know this is currently just searching for the registration string in the array. Is there anyway to search for a specific document reference. I'm using Node.js.
Working code to get all the documents that have a document reference in an array;
// Notify the owner of the car
admin.firestore()
.collection('users')
.where('cars', 'array-contains', carRef)
.get().then(snapshot => {
snapshot.forEach(doc => {
console.log("TESTING found the user " + doc.data().email);
const message = {
notification: {
body: 'Your vehicle (' + carReg + ') recieved a report. Tap here to see!',
},
token: doc.data().cloudMessagingToken
};
sendMessage(message);
});
return
}).catch(error => {
console.error("Error finding a user that has the car in their garage");
console.error(error);
});
If you want to query using reference type fields, you will need to provide a DocumentReference type object to the query. If you pass a DocumentReference to a car, the query should work. For example:
const ref = admin.firestore().collection('Cars').doc(id)
where id is the id of the document.
However, you can't search using values of fields inside the referenced document. Firestore queries only work against data in a single collection at a time. With the way you have your data organized right now, it's not possible to make a single query for all users who have references to cars with a specific registration string field. For that query, you would need to also store an array of registration strings for each user that you could query with array-contains.
Yes, this involves duplication of data, and it's called "denormalization". This is very common in nosql type databases to enable the queries you need.

flutter - add to firestore collection if not exists otherwise update

In flutter, I am using firestore to store my users that log in.
I want if a user login the first time to add his information to a collection.
If he logout, then logs in, I want to update his document in the collection.
To check if there is a document corresponding to the user, I want to check by his 'id' which is a field in the document, and not by the document tag, since I get the 'id' from firebase api.
Here is the add which is working correctly
_firestore.collection('profiles').add({
'firebase_id': profile['user_id'],
'first_name': profile['first_name'],
'last_name': profile['last_name'],
'login_date': profile['login_date']
});
I tried to check if the user exists using the following but it returns always false
bool isEmpty = await _firestore
.collection('profiles')
.where('firebase_id', isEqualTo: profile['user_id'])
.snapshots()
.first
.isEmpty;
Here an example that will check if the users exist or not and if it exists it will overwrite the previous data by simply using merge.
DocumentReference ref = _db.collection('users').document(user.uid);
return ref.setData({
'uid': user.uid,
'email': user.email,
'photoURL': user.photoUrl,
'displayName': user.displayName,
'lastSeen': DateTime.now()
}, merge: true);
}
I hope it will help you
when you save users in the firestore make the documentID equal to userID.
Firestore.instance.collection('profiles').document( profile['user_id']).setData({
'firebase_id': profile['user_id'],
'first_name': profile['first_name'],
'last_name': profile['last_name'],
'login_date': profile['login_date']
});
then check if exists.
bool userExists=(await Firestore.instance.collection('profiles').document('userid').get()).exists;

How to add a document to a collection in cloud firestore

I have a collection called 'users'. I'm trying to add a user to the collection after Google authentication but I keep getting the following error:
FirebaseError: [code=invalid-argument]: Invalid document reference. Document references must have an even number of segments, but users has 1.
Here is the code
this.googlePlus.login({
'scopes': '',
'webClientId': environment.googleWebClientId,
'offline': true,
})
.then(user => {
// save user data on the native storage
const userRef: AngularFirestoreCollection<User> = this.afs.collection<User>(`users/`);
const data: User = {
email: user.email,
displayName: user.displayName,
uid: user.uid
};
userRef.set(data)
.then(() => {
this.router.navigate(['/home']);
Google+ is being discontinued so you should look at Firebase Authentication, or GCP's new Cloud Identity Platform.
In the case of Firebase Authentication, you must listen to the .onAuthStateChanged observer. Once it fires off your user object, you then take that and write a new user document to a users collection in Firestore. Best practise is to use the uid of the firebase.auth().currentUser.uid as the user document ID in your users collection.
Your userRef refers to a collection, and the type of object is called a CollectionReference. You're attempting to call set() on it with some object that should become a new document in that collection. But that's not the way it works. Instead, it looks like you want to call add() to add a new document with a new random ID.
If you somehow already know the ID of the new user document, you should build a DocumentReference with that id, then use set() on that DocumentReference to create the document.

Resources