I have just started developing my first app and have never used Firebase in the past. Before I get too far in to development I would like some advice on how to structure my Firebase data and rules.
The structure/rules need to allow users to upload their own posts, only the owner can update or delete their own posts and posts can be viewed both as a complete list or as a list of posts from the selected user.
A user can also set a post as a favourite, again only they can add or remove a favourite but other users can view a users favourites.
Below is the data structure so far:
{
users:{
'userId1':{ //Firebase assigned ID
'name': "user1",
'email': "user#email.com",
},
'userId2':{
'name': "user2",
'email': "user2#email.com",
}
},
posts:{
'postsId1':{ //Firebase assigned ID
'title': "title",
'message': "message text",
'userId': "userId1"
},
'postsId2':{
'title': "title2",
'message': "message text",
'userId' : "userId1"
},
},
'favourites': {
'userId1': {
'postsId1': "note about favourite",
'postsId2': "note about favourite"
}
'userId2': {
'postsId2': "note about favourite"
}
}
Thanks in advance.
Related
I am trying to make a cloud function.
Whenever i try to hit the endpoint I get 500 Internal Server Error
Postman Response Image here
I've checked logs for firebase functions and i don't see any information there too.
It just says "Function Crashed" without any further information.
I've also checked for any typos and mismatch in the Firestore database structure but it all looks fine to me.
This is the code for firebase function which i uploaded on my Firebase Project.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { error } = require('firebase-functions/lib/logger');
admin.initializeApp(functions.config().firebase);
exports.addEvent = functions.region('asia-east2').https.onRequest(async (req, res) => {
if (req.method === 'POST') {
var db = admin.firestore();
var write = db.collection("Colleges")
.doc(req.body.college)
.collection("events")
.doc(req.body.event.id)
.set({
id: req.body.event.id,
admin: req.body.event.admin,
event_state: req.body.event.event_state,
name: req.body.event.name,
poster_url: req.body.event.poster_url,
start_date_time: req.body.event.start,
end_date_time: req.body.event.end,
location: req.body.event.location,
short_desc: req.body.event.shortDesc,
long_desc: req.body.event.longDesc,
contacts: req.body.event.contacts,
links: req.body.event.links,
});
return res.send(write);
}
else
return res.sendStatus(403);
});
This is the body of the POST Request which i sent from Postman
{
"college": "college_name",
"event": {
"id": 1234,
"admin": "admin",
"event_state": 2,
"name": "Event Name",
"poster_url": "test",
"start": "Date Time",
"end": "Date Time",
"location": "auditorium",
"shortDesc": "lorem ipsum short",
"longDesc": "lorem ipsum long",
"contatcs": [
{
"tag": "Name Tag",
"contact": 12345678
}
],
"links": [
{
"tag": "Link Tag",
"link": 123456784
}
]
}
}
The Firestore Structure is Something like
-Colleges (Collection)
|
|
-Document
|
-events(Collection)
|
-Event Documents (Document which i want to write to ,from the firebase function)
The problem is that your event id in your payload is a number and Firestore documents ids must be strings. So you either, use .doc(req.body.event.id.toString()) or you send your event id as string in your payload id: "1234".
Also, consider refactoring your code following Firebase guidelines to handle the POST method.
I have a schema in sequelize that a user has many tokens, I need to get all users and for each user, I need to have all tokens. The id of user is saved in Token table as FK.
I created this below but did not work
await Model.Users.findAll({
attributes: ['id'],
include: [
{
model:Model.Token,
attributes: ['token']
}
]
});
The response I want to have back is like below
[
{ id: 2, Tokens: [{token: sdasdasdasdweqrewrfwe}, {token: test}] },
{ id: 6, Tokens: [{token: test2}, {token: test3}] },
.
.
]
Thanks
Problem was not in code but in sequelize table connection, if you have same problem please check the connection
db.User.hasMany(db.Token, {
onDelete: "CASCADE",
onUpdate: "CASCADE",
foreignKey: 'user_id'
});
First of all I know NOSQL systems do not have JOIN. But I know there is a way for getting a datas with another table values.
About my app:
This app is basic social network app. People can share photos. These posts saving firebase database 'realtime database' not cloud firestore than it has a timeline page. this page shows shared posts. I need to show posts with publisher information.
Users login with firebase authentication and I have users table called kullanici like this.
I have Posts table like this.
I need to delete displayName in Posts table than get isim in kullanici table.
my needed data is: Post with kullanici->{posts.{postid}.userid}->isim.
my working code is below:
return (dispatch) => {
firebase.database().ref(`/posts`).endAt("tarih").limitToLast(2)
.on('value', snapshot => {
dispatch({type: STUDENT_LIST_DATA_SUCCESS, payload: snapshot.val()});
});
};
my returned data is below:
Object {
"-L9tnfvm6jQiKLc378c6": Object {
"aciklama": "",
"baslik": "Ensar mı Ahmet mi",
"displayName": "HasanRiza",
"image": "https://hasan-riza-uzuner.s3.amazonaws.com/1523535677033.png",
"like": 244,
"tarih": 1523535757133,
"userid": "fD7IfKAhXogFwHtfKYiF7LMtXNp1",
},
"-LYHPJgR4sywTzpcxX7A": Object {
"aciklama": "Ev",
"baslik": "Nasıl",
"displayName": "HasanRiza",
"image": "https://hasan-riza-uzuner.s3.us-east-2.amazonaws.com/1549718296409.png",
"like": 1,
"tarih": 1549718342522,
"userid": "fD7IfKAhXogFwHtfKYiF7LMtXNp1",
},
}
var promises = [];
group_ids.forEach(function (group_id) {
promises.push(firebase.firestore().collection('Group').doc(group_id).get())
});
Promise.all(promises).then(function(docs) {
docs.forEach((groupDoc) => {
group.name = groupDoc._data['name'];
group.city = groupDoc._data['city'];
group.state = groupDoc._data['state'];
groups.push(group);
});
console.log(groups);
});
I'm trying to add security rules to a new Firestore project I'm working on. I have a collection named users that has all my user data in it in this format in my Firestore database:
var users = {
"userId": {
friend_requests: [],
friends: [
/users/friendId1,
/users/friendId2
],
name: "User One",
username: "user1"
},
"friendId1": {
friend_requests: [],
friends: [
/users/userId
],
name: "User Two",
username: "user2"
},
"friendId2": {
friend_requests: [],
friends: [
/users/userId
],
name: "User Three",
username: "user3"
},
"lonelyUser": {
friend_requests: [],
friends: [],
name: "Lonely User",
username: "lonely_user"
}
}
My Firestore rules are this, verbatim:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /users/{userId} {
allow read: if isOwner(userId) || isFriendOf(userId);
}
}
function isOwner(userId) {
return userId == currentUser().uid;
}
function isFriendOf(userId) {
return getUserPath(userId) in getUserData().friends;
}
function currentUser() {
return request.auth;
}
function getUserData() {
return get(getUserPath(currentUser().uid)).data;
}
function getUserPath(userId) {
return /databases/$(database)/documents/users/$(userId);
}
}
The keys in the map I outlined above are Firebase user ids in my actual db, so when logged in as user "userId" I'd expect to be able to read the user document for both "friendId1" and "friendId2" users.
The problem I'm having is that isFriendOf is returning false. I've tried a few variants of wrapping the comparison data in a get call and passing in other values like id and data off the resource it returns.
I've also tried wrapping the getUserPath call in isFriendOf in a get and then using the __name__ property of the document as the comparison value as well. No luck there either.
Any help would be greatly appreciated.
Edit: Including a screenshot of the actual documents for clarification.
Screenshot of Firebase Documents
Edit 2: I've made a clean firebase project with only the information in these new screenshots in it. I'm including screenshots of Firebase Authentication page, both user entries in the database, as well as a failed simulator run as one user trying to get the document of the other user.
Authentication Configuration
user1
user2
Simulated Request
i've been developing a mobile app with react native & firebase realtime db, and i'm stuck with a data-modeling problem.
My app will let users to vote photos that uploaded by other users and each user will be allowed to vote once for each photo. I'm providing a tinder-like UI for voting action. I'm planning to have users and photos trees on the firebase looks like this, which is pretty straight forward:
{
users:{
userId1: {
name:'John'
surname: 'Doe',
votedPhotos: {
somePhotoId: {
timestamp: 1528836856000
},
somePhotoId2: {
timestamp: 1529363754000
},
...
},
...
},
userId2: {
name:'Johnny'
surname: 'Doerr'
...
},
...
},
photos: {
photoId1: {
url: 'https://a-firebase-storage-url',
owner: {
uid: 'userId1',
fullName: 'John Doe'
},
upvoteCount: 12,
downvoteCount: 8
},
photoId2: {
url: 'https://another-firebase-storage-url',
owner: {
uid: 'userId2',
fullName: 'Johnny Doerr'
},
upvoteCount: 28,
downvoteCount: 4
},
...
}
}
I need to prevent users to vote their own photos and vote a photo more than once. So i need to query photos as excluding already voted photos and self uploaded photos for a user. If i was using a traditional db it would be easy as a pie but i couldn't figure out how to do that query in a firebase realtime database since i can't use not_equals or not_in. How would you suggest me to model my data?
Record user votes under the photouid. I imagine a .length could provide you the total votes.
photos
photo1-uid
owner:user1-uid
votes:{
user2-uid: true,
user3-uid: true
}