Finding random (auto) id assigned to our document by Firestore - java

I know its a bit weird question but how can I access the unique (auto) id google firebase generates for my document whenever I create new document. For example this is my code
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
How can I know that what is the id generated for this document of "newPost" because i want to use that id in my code and at the same time i dont want to send custom id because it won't be unique

val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
As you've likely discovered, .set() returns a Promise <void> .
But what you've ignored is .set() only operates on a DocumentReference - which is what you get from postCollections.document(). A DocumentReference has properties id and path - it is the .document() that creates a new, unique, documentId.
So:
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
val newRef = postCollections.document()
newRef.set(newPost)
And now you have the document id (and path) available as properties of newRef.
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference

Related

How to check a phonenumber that already added to the firestore database?

Here in the Firestore databases is a collection called "Users", In that collection, there are 29 documents(States) and in each of that documents there are many collections(Districts). This collection includes many documents these documents include the user's data along with numbers).
so how do we check the phone number that has already been added to the database?
I write something like this
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
CollectionReference usersRef = firestore.collection("Users");
String phoneNumber = "1234567890";
usersRef.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Map<String, Object> data = document.getData();
for (String key : data.keySet()) {
Object value = data.get(key);
if (value instanceof String && ((String) value).equals(phoneNumber)) {
isRealAvailable = true;
Toast.makeText(OtpActivity.this, "Number found", Toast.LENGTH_SHORT).show();
// Phone number found
break;
}
}
}
} else {
isRealAvailable = false;
Toast.makeText(OtpActivity.this, "No number found, create an account!", Toast.LENGTH_LONG).show();
}
// Handle error
}
});
(the number is not a String value)
I don't know how to retrieve these details from different document names.
How do we get the Phone Number from the document? if it exists.
What I wanted is, I'm building a blood donors app, where people can register using their phone numbers. From different countries. So when a user sign-up with proper details, he can go to the main screen. Whenever he logout and login, he doesn't need to update the details again. As we know phone number login and signup are the same. Also, I want to separate the states and places in different documents and collections. I added the location permission and perspective codes so the country and states are chosen automatically. (will get the users location)
When you're calling get() on the following collection reference:
CollectionReference usersRef = firestore.collection("Users");
It means that you're trying to get all user documents that exist in the Users collection. As soon as you get all users, you then check the phoneNumber against the one that you find in the database, which is bad since you'll need to pay for a document read even for the users that do not have that particular phone number. What you have to do instead is to create a query that should only return the documents that you are interested in.
On the other hand, your actual database schema isn't quite helping you to achieve that. In the NoSQL world, we are usually structuring a database according to the queries that we want to perform. So if you need to get all users from Brooklyn / New York that have a particular phone number, I would recommend you have a schema that looks like this:
db
|
--- users (collection)
|
--- $uid (document)
|
--- city: "New York"
|
--- borough: "Brooklyn"
|
--- mobNumber: 720555
And in code, it should look like this:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference usersRef = db.collection("users");
Query queryByMobNumber = usersRef.whereEqualTo("city", "New York")
.whereEqualTo("borough", "Brooklyn")
.whereEqualTo("mobNumber", 720555);
queryByMobNumber.get().addOnCompleteListener(/* ... /*);
So in Firestore, chaining multiple whereEqualTo calls will work perfectly fine.
Besides that, I see that you are changing a boolean value inside the callback, which will not be seen outside the callback because Firebase API is asynchronous. If you want to learn more about that, I recommend you check this resource. Here is the corresponding repo.

kotlin android get deleted value from realm-java

I use realm-java on Android. now I'm creating profile function, but I'm not sure how to user realm correctly.
when renew profile,
delete value -> store value
but, I fetch value from realm, sometimes old value is taken.
To reproduce,
My test repository is below, and I attached movie that problem is reproduced.
https://github.com/shinsan/realm_test/
When thread id is changed, sometimes old value appears.
so, if you try to reproduce, please use lower memory device such as nexus5 simulator
#I think Realm instance is singleton and transaction is thread-safe, so value is always only one.
my code
kotlin + Android Studio
Realm Java 10.3
//Store
val realm = Realm.getDefaultInstance()
realm.executeTransaction {
val entity = AccountProfileEntity(accountProfile)
it.copyToRealmOrUpdate(entity)
}
//Delete
val realm = Realm.getDefaultInstance()
val entity = realm.where(AccountProfileEntity::class.java).findFirst()
realm.executeTransaction {
entity?.deleteFromRealm()
}
//Fetch
val realm = Realm.getDefaultInstance()
val instance = realm.where(AccountProfileEntity::class.java).findFirst()
return instance?.toModel()
// profile get function
override suspend fun getProfile(isForce: Boolean): AccountProfile =
withContext(Dispatchers.IO) {
if (isForce) {
database.delete()
}
val profile = database.fetch()
if (profile != null) {
return#withContext profile
}
val token = prefs.getToken() ?: throw NoTokenException
val response = service.getProfile(token)
database.store(response)
response
}
Please Help
I solved this. simply I forgot to close realm instance each fetch, store, delete.

how to get unique document path as a string?

The code below generates a document with a unique document path. how do I get this unique document path?
db.collection("Jobs").document().set(job);
this is the #kotlin code to get ID of document that created by .add() function
FirebaseFirestore.getInstance()
.collection(collectionReferencePath)
.get().addOnSuccessListener { querySnapshots ->
querySnapshots.documents.forEach { documentSnapshot ->
val idUnique = documentSnapshot.id //This is the Unique Id
}
}.addOnFailureListener {
it.printStackTrace()
}
If you set the set to a variable, after it resolves you can run .id on it which will give you its id.
At that point, the path is something you could create by doing "Jobs/" + id.
I know the below is Javascript code and not Java (like the tag on your question), but it should work something like this:
let doc = db.collection("Jobs").doc()
doc.set(job).then(() => {
let id = doc.id
})

How do I get randomly generated userID from .push() in Firebase

Currently I am adding my user class to a firebase database using this code:
public void onClick(View v)
{
Firebase ref = new Firebase("https://xxxxxx.firebaseio.com/");
createAccount(emailString, passwordString);
User user = new User ();
user.setEmail(emailString);
user.setPassword(passwordString);
ref.child("users").push().setValue(user);
}
Right now, since I use the .push() method, I am creating a unique ID in my database. How do I pull that unique ID? I looked at this tutorial but I don't understand how to implement it.
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); //get the reference to your database
User user = new User ();
user.setEmail(emailString);
user.setPassword(passwordString);
String yourKey = dbRef.child("users").push().getKey(); //get the key
dbRef.child("users").child(yourKey).setValue(user); //insert user in that node
But if you want to access that node (yourKey) later, you will need to store it in some sort of permanent storage like a database on your web server.
Great example of how to get key check these docs out helped me a lot.
Firebase Docs
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;

how to retrieve ID after object store into database

I am using Java, spring, jpa for our application. I want to retrieve Id of insert row. Basically our ID is generated at the time of storing object into database.
RoleRequest role = new RoleRequest();
roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(Enum.PENDING);
Dao.persist(roleRequest);
So after storing this object, I need new generated id for this object, so that will perform some operation on it.
Dao.persist(roleRequest);
After this line, the id should be set, so you can just do
Long id = roleRequest.getId();
(assuming id as id column and Long as id type)
What about:
oleRequest role = new RoleRequest();
roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(RoleRequestStatusEnum.PENDING);
Dao.persist(roleRequest);
int myId = roleRequest.getId();
You may need to do EntityManager.flush() after EntityManager.persist() (YMMV).

Categories