How to make transactions on multiple data tables in Firebase? - swift

I've an application, which uses Firebase. I have a new post adding. And when I make it, I do a number of operations in database, like:
Add new post info to Posts node
Add Id of the new post to Users node
Upload media to storage
etc.
So, for example, user can close application on step 2. How can I reset data on start of adding new post?
If I've understood correctly, Firebase transactions work on only one data table.
Main question is: how to make transactions on multiple data tables and storage in Firebase?

I believe you're looking for something like this: https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields. It allows you to run multiple updates all at once to wherever you need. Here is a snapshot of the code:
var updates = {};
updates['/posts/' + newPostKey] = ...;
updates['/user-posts/' + uid + '/' + newPostKey] = ...;
return firebase.database().ref().update(updates);

Related

Check for existing value inside of Firebase Realtime Database

Hello, I have a problem I created a Registration form and im trying to check if there is any user which have a certain username inside the Firebase Db. I tried to get the reference of all the users.
var users = Database.database().reference("users")
But I don't know how I could check if there is any user with a specified username.
You'll want to use a query for that. Something like:
let query = users.queryOrdered(byChild: "username").equalTo("two")
Then execute the query and check whether the result snapshot exists.
Note though that you won't be able to guarantee uniqueness in this way. If multiple users perform the check at the same time, they may both end up claiming the same user name.
To guarantee a unique user name, you will need to store the user names as the key - as keys are by definition unique within their parent node. For more on this, see some of these top search results and possibly also from here.

How can I retrieve all row of one column in firebase flutter

I am trying to make a firebase database call to retrieve all row of one particular column in the firebase database of my app and display it in a textbox in my flutter app.
That is, to retrieve all phone numbers in the Users table.
For instance, in SQL we can do like this:
SELECT (PhoneNumers) FROM Users
I am new in flutter/dart, I need some help.
Its really easy.
First of all, setup and initialize firebase in you project. Then make a function and create an instance of firestore like this
FirebaseFirestore firestore = FirebaseFirestore.instance;
Then make something called Collection reference:
CollectionReference users = await firestore.collection("users").get().then((querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["PhoneNumber"].toString())
});
This will grab every collection from Users, loop over them and then print out the document PhoneNumber to console. There is no way to just get a single document field from firestore. It might seem weird, but its quite useful at times. Right now, you have access to every document field of every user of your app.

React Native game, MongoDB or Firestore

I am working on a multiplayer react native game for android, it's just a text game.
For now, I've been working only on the client side but I'm slowly getting to the point where I need to choose a way to manage data. Since I'm always trying to learn something new - first time using RN too -, I came across Firestore and I'm curious if it's a viable choice from my project.
For example, in this game you can buy/open companies. If I were to handle this action in nodejs + MongoDB I'd send a JWT token to server/api/newcompany.
Assuming I'd have 2 MongoDB models, Users with all the user info and Company a list of all Companies in game. First I'd check if the User had enough money to open the company and then return some message based on that, my code would be something like this:
// routes.js
...
router.post('/api/newcompany',AuthCheck, Company.new)
// controllers/company.js
...
new: async function (req, res, next) {
if (!req.body.companyType || !validCompanyType) {
return res.status(200).send('invalid/missing message and other failed checks')
}
//assuming token data would be passed from auth middleware and would have company prices somewhere
const user = await Users.find({id:token.userId})
if (user.money < companyPrice) {
res.status(200).send('no money')
} else {
const newCompany = new Company()
newCompany.name = req.body.name
...
new.Companny.save(function(){
res.status(200).send('all good')
})
}
}
Looking at Firestore I'd have the same 2 documents as above. Users with a list of sub-documents(the users) identified by their IDs and a document Companies.
Would I be able to do the same users checks as above?
How would I handle that? Would I use the Firestore Rules to check the user has enough money or would I use my server with admin SDK as an intermediary to handle more complex ops and use the direct Firestore connection just for retrieving data?
Thanks for your time.

How to set more than one value to a child in Firebase using Swift?

I am trying to make a money related app which shows the user their spendings as a project to get used to Firebase. So I stumbled upon this issue; I can't seem to figure out how to add more than one expense assigned to a user. Whenever I add a new expense, the existing value in Firebase gets reset to the new value but I want it to store both the new and the old value. How can I do this?
There's something called "autoID" if that helps. I'll link that in a few moments.
Edit: It's used here.
childByAutoId() is what you want for swift. See Updating Or Deleting specific data section in the Read and Write Data on iOS
let thisUserRef = ref.child("users").child(users uid)
let expenseRef = thisUserRef.child("expenses").childByAutoId()
let dict = ["expense_type": "travel", "expense_amt": "1.99"]
expenseRef.setValue(dict)
will results in
users
uid_0
-Y88jn90skda //<- the node key created with childByAutoId
expense_type: "travel"
expense_amt: "1.99"
the childByAutoId is super powerful and allows 'random' node keys to be generated that contain your child data.
See the answer to this question and this other question for some tips on data modeling and queries.

How can I have an association fetch an existing record?

I'd like to write a factory for a blog post, that doesn't create a new user record for every post, but rather pick a random user from those that already exist. How would I do this?
You could randomly order your table, take a record and assign it to your Post. Bear in mind that there is definitely a cleaner way to do this, but here's one that works, obviously assuming your users are already in your test database.
user = User.order("RANDOM()").take #PostgreSQL
user = User.order("RAND()").take #MySQL
post = create(:post, user: user)