I have an invoice object that has an account object inside it. When displaying the invoice to a user, I have the following object:
invoice : {
Number : 1234,
Account : { id: 12345,
name: "Test account"
}
}
When saving an invoice, the user can select the account from a drop down. In that case, all I really need is the id of that account so my object will look something like this:
invoice : {
Number : 1234,
AccountId : 12345
}
My question is: Do I need to create two different objects one for saving and another one for displaying the invoice? If not, how would you handle this?
Thanks!!
Create another property "AccountId" in same javascript object and delete unwanted property just before saving it.
invoice.AccountId = invoice.Account.id;
delete invoice['Account'];
Related
Suppose I have an app where a user can select a car to be stored in a table like car_used_today or something (persisting Car and Date). I want my app to provide default cars (say, popular ones) as options, but have a form where the user can create custom cars to add to the dropdown (e.g., a new car company is created and I don't intend to support it as dev). These are stored in a custom_car table.
What is the best way to model this and persist a user selection that could be an app-provided option or a custom one.
My first pass (assuming Kotlin) is something like
sealed class Car {
object BMW : Car()
object Mercedes : Car()
data class Custom(private val id: Int, private val name: String) : Car()
}
In TS we might do
type Car = 'BMW' | 'MERCEDES' | { id: number, name: string }
Now I can write all my functions to take Car. Awesome!
But that runs into a persistence problem: How would I store user's car selection in car_used_today? Neither BMW or Mercedes has an id prop. I could add one, but would have to pick an id for each that a database wouldn't generate automatically. So if the table's id field is auto-incrementing integer, I could pick an arbitrary negative number as id for the non-customs.
But this feels like a code smell, albeit maybe only a slightly pungent one.
I could also get rid of the sealed class and go with just
data class Car(private val id: Int, private val name: String)
and then seed the DB with BMW and Mercedes entries. But this smells even worse, hard-coding defaults into a DB when they could be in the code and divorced from the DB completely. Why even worry about data persistence for known app-provided options?
Yes, if the user would be permitted to delete the defaults so they never show up, it makes sense for them to be in the DB so they the rows can be DELETEd. But if we don't want them to be removed ever, it's a different issue.
This cannot possibly be a novel issue. So what is the best practice for this?
Recently I moved my data model from Firebase to Firestore. All my code is working, but I'm having some ugly troubles regarding my nested queries for retrieve some data. Here is the point:
Right now my data model for this part looks like this(Yes! Another followers/feed example):
{
"Users": { //Collection
"UserId1" : { //Document
"Feed" : { //Subcollection of Id of posts from users this user Follow
"PostId1" : { //Document
"timeStamp" : "SomeDate"
},
"PostId2" : {
"timeStamp" : "SomeDate"
},
"PostId3" : {
"timeStamp" : "SomeDate"
}
}
//Some data
}
},
"Posts":{ //Collection
"PostId1":{ //Document
"Comments" :{ //Subcollection
"commentId" : { //Document
"authorId": "UserId1"
//comentsData
}
},
"Likes" : { //Subcollection
"UserId1" : { //Document
"liked" : true
}
}
}
}
}
My problem is that for retrieve the Posts of the feed of an user I should query in the next way:
Get the last X documents orderer by timeStamp from my Feed
feedCol(userId).orderBy(CREATION_DATE, Query.Direction.DESCENDING).limit(limit)
After that I should do a single query of each post retrieved from the list: workoutPostCol.document(postId)
Now I have the data of each post, but I want shot the username, picture, points.. etc of the author, which is in a different Document, so, again I should do another single query for each authorId retrieved in the list of posts userSocial(userId).document(toId)
Finally, and not less important, I need to know if my current user already liked that post, so I need to do a single query for each post(again) and check if my userId is inside posts/likes/{userId}
Right now everything is working, but thinking that the price of Firestore is depending of the number of database calls, and also that it doesn't make my queries more simple, I don't know if it's just that my data model is not good for this kind of database and I should move to normal SQL or just back to Firebase again.
Note: I know that EVERYTHING, would be a lot more easier moving this subcollections of likes, feed, etc to arraylists inside my user or post documents, but the limit of a Document is 1MB and if this grow to much, It will crash in the future. In other hand Firestore doesnt allow subdocument queries(yet) or an OR clause using multiple whereEqualTo.
I have read a lot of posts from users who have problems looking for a simple way to store this kind of ID's relationship to make joins and queries in their Collections, use Arraylists would be awesome, but the limit of 1MB limit it to much.
Hope that someone will be able to clarify this, or at least teach me something new; maybe my model is just crap and there is a simple and easiest way to do this? Or maybe my model is not possible for a non-sql database.
Not 100% sure if this solves the problem entirely, since there may be edge cases for your usage. But with a 5 min quick thinking, I feel like the following could solve your problem :
You can consider using a model similar to Instagram's. If my memory serves me well, what they use is an events-based collection. By events in this specific context I mean all actions the user takes. So a comment is an event, a like is an event etc.
This would make it so that you'll need three main collections in total.
users
-- userID1
---- userdata (profile pic, bio etc.)
---- postsByUser : [postID1, postID2]
---- followedBy : [userID2, ... ]
---- following : [userID2, ... ]
-- userID2
---- userdata (profile pic, bio etc.)
posts
-- postID1 (timestamp, so it's sortable)
---- contents
---- author : userID1
---- authorPic : authorPicUrl
---- authorPoints : 12345
---- taggedUsers : []
---- comments
------ comment1 : { copy of comment event }
---- likes : [userID1, userID2]
-- postID2 (timestamp)
---- contents
...
events
-- eventID1
---- type : comment
---- timestamp
---- byWhom : userID
---- toWhichPost : postID
---- contents : comment-text
-- eventID2
---- type : like
---- timestamp
---- byWhom : userID
---- toWhichPost : postID
For your user-bio page, you would query users.
For the news feed you would query posts for all posts by userIDs your user is following in the last 1 day (or any given timespan),
For the activity feed page (comments / likes etc.) you would query events that are relevant to your userID limited to the last 1 day (or any given timespan)
Finally query the next days for posts / events as the user scrolls (or if there's no new activity in those days)
Again, this is merely a quick thought, I know the elders of SOF have a habit of crucifying these usually, so forgive me fellow members of SOF if this answer has flaws :)
Hope it helps Francisco,
Good luck!
I am making an application with azure mobile services which stores users hours and points in a table called attended users. The problem I have is when I try and update the one specific user it selects all of the users with the same club id. I need an update function that finds a user with a club id and UniqueUserID that are unique, then updates the hours and points based on the one result.
Controller Code
$scope.saveChanges = function(){
$scope.show($ionicLoading);
var query = client.getTable('AttendedClubs').update({id: clubID.getJson(), UniqueUserID: memberID.getJson(), Hours: $scope.profile.Hours, Points: $scope.profile.Points}).done(function(results) {
$scope.hide($ionicLoading);
}, function(error) {
$scope.hide($ionicLoading);
alertDialogue.pop("No Internet Connection","Check Connection");
});
}
You are using a unique ID of the clubID. You need to construct this. When you create your object, do something like:
var table = client.getTable('AttendedClubs');
table.insert({
id: uuid.v4(),
clubID: clubID.getJson(),
UniqueUserID: memberID
...
});
To update all records, first do a fetch, then do an update on a per-record basis. Use the id to uniquely identify the record.
I have a reservation system and I want to store the user_id of people who buy the tickets of an event, with the number of tickets bought in an array of hashes. So, it would be like:
[{"id" => "1", "no" => "3"}, {"id" => "4", "no" => "2"}]
It means that user_id 1 reserved 3 seats in this event ...
The database I'm using is PostgreSQL and I defined this field as text, array: true with the name of reservations to use the power of array in psql.
The problem is to search this field to show each user his reservations and corresponding quantity. I need to define a scope in the Event model and call it from the User controller. As a result, each user can see his reservations in his dashboard. I tried many many ways but still have problem. Any idea and help would be great.
How about creating separated table and store there user_id and seats_count. You can name it UserReservation. You can then update User model and have
class User
has_many :user_reservations
end
so you can easily fetch all user reservations by calling current_user.user_reservations.joins(:event)
I need to use the look up field which relates Contact and Account object in Trigger. I have lookup field Account__c on the Contact, but I cannot get the related Account for that contact when I write something like
Map <Id,Account> acts = new Map<Id,Account>([Select Id,Name from Account where Id:=contact.Account__c]);
it should get all related accounts in to acts, but it does not work..
How can I get related Accounts?
Unless this is a special case you don't need to create a relationship between contact and account, there is already a standard one. you can query it like so
try {
Account parent = [SELECT Id, Name FROM Account WHERE Id = :contact.AccountId];
} catch(QueryException e) {
//list has no rows for assignment
//means the account with Id could not be found
}
For more information about the api names you should look at the wsdl
As an aside, you don't need to pass the results of this query to a map, any time you use Id = :idValue in a WHERE clause it is guaranteed that you will get exactly 0 or 1 result, and in the cause of 0 results a QueryException will be thrown.