Firestore - How create DocumentReference using path String - android

Firebase realtime database allowed to create refrence using
var reference = db.ref(path);
Is there any method exist in firestore so that I can create document refrence using path String.
If method exists how can I find path string in android and then how create document reference in node.js using that path.

Yes, you can achieve this also in Cloud Firestore. So these are your options:
FirebaseFirestore db = FirebaseFirestore.getInstance();
First option:
DocumentReference userRef = db.collection("company/users");
Second option:
DocumentReference userRef = db.document("company/users");
Third option:
DocumentReference userRef = db.collection("company").document("users");

For web/javascript, db.doc() will create a DocumentReference from a string:
let docRef = db.doc(pathString)
e.g. let userRef = db.doc('users/' + userId)

You can use FirebaseFirestore.document() and pass it the path of the document you want. Each document must be located within a collection. If you're looking for a document called documentId in a collection called collectionId, the path string will be collectionId/documentId.

you just need to define the path :
`users/${type}/${user.uid}/`
firestore
.collection(`users/${type}/${user.uid}/`)
.add(documentData)
.then(function () {
message = { message: "document added", type: ErrorType.success };
})
.catch(function (error) {
message = { message: error, type: ErrorType.error };
});

For Firestore web version 9 (after August 25, 2021) you can use doc() to generate a reference with an id:
import { collection, doc, setDoc, getFirestore } from "firebase/firestore";
// Add a new document with a generated id
const newRef = doc(collection(getFirestore(), "user"));
const data = {
id: newRef.id,
firstName: 'John',
lastName: 'Doe'
}
await setDoc(newRef, data);

Use "." instead of "/" for path
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection(FBConstant.Product.Head)
.whereEqualTo("rating.$id", true)

Related

Why is array empty when running Android Studio?

I am using react native and firebase realtime database to store and query a list of properties. It seems that when I run the below query in XCode for iOS the array created here shows a list of the property objects. However, when I run this android studio the array is empty. Do you know what may be causing this? Can someone please help here I am very new to react native and using firebase realtime database?
I really do apologies for the poor code formatting:
const array = []
await db.ref(`users/`).on(`value`, snapshot => {
if (snapshot.exists()) {
snapshot.forEach(function(userSnapshot){
if(userSnapshot.hasChild("properties")){
userSnapshot.child("properties").forEach((propertySnapshot) => {
array.push({
key: userSnapshot.key,
property: propertySnapshot.val(),
username: userSnapshot.val().username,
email: userSnapshot.val().email,
phoneNumber: (userSnapshot.val().phoneNumber != null)?userSnapshot.val().phoneNumber:null,
propertyName: propertySnapshot.key,
profile_pic: userSnapshot.val().profile_pic,
connectedAccount_id: (userSnapshot.val().connectedAccount_id != null)?userSnapshot.val().connectedAccount_id:null,
customer: (userSnapshot.val().customer != null)?userSnapshot.val().customer:null,
});
})
}
})
}
});
await database().ref(`users/${auth().currentUser.uid}/your_location`).once(`value`, function(snap){
....
Geocoder.init("******");
Geocoder.from(locationPostcode)
.then(json => {
var location = json.results[0].geometry.location;
global.latitude = location.lat;
global.longtitude = location.lng;
})
.catch(error => console.warn(error));
console.log("array result "+array)
.....
})
The log array shows an array of objects for iOS:
array result [object Object],[object Object],[object Object],[object Object],[object Object]
but for android it's empty:
array result

how to search through all documents for a specific field value

how to search through all documents for a specific field value
for eg: if i want the field: blood_group 'A+' from all documents and show me all documents which has 'A+' in it
https://i.stack.imgur.com/0IhT9.png
https://i.stack.imgur.com/4tkEG.png
source code
You can use the .where filter on the collection reference's query like below:
final QuerySnapshot querySnapshot = await FirebaseFirestore.instance.collection('users').where('blood_group', isEqualTo: 'A+').get();
final List<QueryDocumentSnapshot> documentSnapshotList = querySnapshot.docs;
for (QueryDocumentSnapshot snapshot in documentSnapshotList) {
print(snapshot.data());
}
You can use the .where option. Based on your firebase structure in the picture, you can use the following code, to get a list of all documents that satisfy your request.
Future<QuerySnapshot> bloodgroup (String bloodGroup) async {
return await FirebaseFirestore.instance.collection('Donation').where('blood_group', isEqualTo: bloodGroup).get();
}
void getDocs() async {
QuerySnapshot allResults = await bloodgroup('A+');
for (var item in allResults){
print(item.id); //this will print the id of all the documents which are A+.
}
}

Flutter Firestore [cloud_firestore/not-found] Some requested document was not found

In my flutter app I need to update my current user data but I have this issue [cloud_firestore/not-found] Some requested document was not found. how can I fix this
here my updateData() code
void updateData() {
final FirebaseAuth auth = FirebaseAuth.instance;
final User user = auth.currentUser;
final uid = user.uid;
FirebaseFirestore.instance.
collection('users').
doc(uid).
update({"height": heightTextEditingController.text}).
catchError((e) {
print(e);
});
}
Take a screenshot of your Firestore so that we can see what's your Firestore directory names. Could be a spelling mistake.
Edit 1:
Found the mistake. It should be FirebaseFirestore.instance.collection('users') instead of ('user'). See below codes
FirebaseFirestore.instance.
collection('users').
doc(uid).
update({"height": heightTextEditingController.text}).
catchError((e) {
print(e);
});
}
You need to add the uid as a document id when saving data to the database:
var firestoreInstance = FirebaseFirestore.instance;
var firebaseUser = FirebaseAuth.instance.currentUser;
firestoreInstance.collection("users").doc(firebaseUser.uid).set(
{
"name" : "john",
"email" : "example#example.com",
"height": 180
"weight":70
}).then((_){
print("success!");
});
Inside doc() pass the uid and then use set() to add the fields to the document.

OrderBy Statement for Subfields on Firebase in Flutter

I have a collection of following;
I want to return every company in ascending order by companyName and this is how I'm trying;
QuerySnapshot usersComp = await _firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
.orderBy({
'properties': {'companyName'}
}, descending: false).getDocuments();
Code doesn't give any errors but it also doesn't return any value as well. The statement without orderBy works fine.
How can I write a this orderBy in a working way?
edit
This is the whole getCompanies function in FirebaseCrud:
Future<List<Company>> getCompanies() async {
FirebaseUser curruser = await _authService.getCurrentUser();
DocumentSnapshot userSnapshot = await Firestore.instance
.collection('users')
.document(curruser.uid)
.get();
List partners = userSnapshot.data['partners'];
print('partners');
print(partners[0]);
QuerySnapshot usersComp = await _firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
//.orderBy('properties.companyName', descending: false) // code works fine without this line but not as expected
.getDocuments();
List<Company> companies = new List<Company>();
usersComp.documents.forEach((f) {
int indexOfthis = usersComp.documents.indexOf(f);
companies.add(new Company(
uid: partners[indexOfthis],
companyName: f.data['properties']['companyName'],
address: f.data['properties']['address'],
paymentBalance: f.data['currentPaymentBalance'],
revenueBalance: f.data['currentRevenueBalance'],
personOne: new Person(
phoneNumber: f.data['properties']['personOne']['phoneNumber'],
nameAndSurname: f.data['properties']['personOne']
['nameAndSurname']),
personTwo: new Person(
phoneNumber: f.data['properties']['personTwo']['phoneNumber'],
nameAndSurname: f.data['properties']['personTwo']
['nameAndSurname']),
));
});
return companies;
}
Use dot notation to reference properties of objects to use for sorting.
_firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
.orderBy('properties.companyName'),
descending: false)
I created a collection with a few documents, each have a top-level field and a nested field. If I then run a query over it like this:
Firestore.instance.collection("59739861")
.where("location", isEqualTo: "Bay Area")
.orderBy("properties.companyName", descending: false)
.getDocuments().then((querySnapshot) {
print("Got ${querySnapshot.documents.length} documents");
querySnapshot.documents.forEach((doc) {
print("${doc.documentID}: ${doc.data['properties']}");
});
});
I have added these three documents in my database:
location: "Bay Area", properties.companyName: "Google"
location: "Bay Area", properties.companyName: "Facebook"
location: "Seattle", properties.companyName: "Microsoft"
With the above query, I get the following output printed:
flutter: KJDLLam4xvCJEyc7Gmnh: {companyName: Facebook}
flutter: TMmrOiKTYQWFBmJpughg: {companyName: Google}
I have no idea why you're getting different output.
Just in case it matters, I run the app in an iOS simulator and use this version of the Firestore plugin:
cloud_firestore: ^0.13.0+1

Get document id from firebase flutter

I trying to get the new created document id after data has been stored to firebase database, but get error
E/flutter (20333): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'listen' was called on null.
E/flutter (20333): Receiver: null
E/flutter (20333): Tried calling: listen(Closure: (String) => void)
send_data_bloc
_repository
.addOrder(order)
.listen((documentId) => print(documentId));
repository
#override
Observable<String> addOrder(Order order) {
var a = endpoints.collectionEndpoint.add(order.toJson());
a.then((val) {
return Observable.fromFuture(val.documentID());
});
endpoints
#override
get collectionEndpoint => _firestore
.collection(collectionName)
.document(this.id)
.collection(orderCollectionName);
Ideally you should return the future from the repository and await for the future on the bloc. Let me try to give a full code snippet here. It would be something like this:
send_data_bloc
final documentId = await _repository
.addOrder(order);
print(documentId);
return documentId;
repository
#override
Future<String> addOrder(Order order) {
return endpoints.collectionEndpoint.add(order.toJson());
endpoints
#override
get collectionEndpoint => _firestore
.collection(collectionName)
.document(this.id)
.collection(orderCollectionName);
Here
a.then((val) {
return Observable.fromFuture(val.documentID());
});
you are returning the observable within the then function, i believe this is not the expected behavior.
One thing you should do to improve your code quality and readability is to just user async/await. The function on the repository can be rewrited like that:
#override
Observable<String> addOrder(Order order) async {
var documentID = await endpoints.collectionEndpoint.add(order.toJson());
return Observable.fromFuture(val.documentID());
Try this. This should do the trick.
Whats the reason why you are using Observables? Is this a firebase thing?
You could adjust to:
final var documentId = await _repository.addOrder(order);
print(documentId)
i had the same problem here is a snippet of how i approached it
//notice im using add while referencing the document reference
final DocumentReference documentReference=await Firestore.instance.collection('jobs').add({
'jobid':"",
});
then get your id from documentReference
final String jobIdd=documentReference.documentID;
after getting the id now you can add your document to cloud firestore
Firestore.instance.collection('jobs').document(jobIdd).setData({
'category': category,
'description': description,
'datePosted': formattedDate,
'postedby': userid,
'jobid':jobIdd,
});

Categories

Resources