sequelize to create better database structure - javascript

i am trying to think of a database for a project similar to netflix. where you can login on multiple devices and for each device you have a token.
the problem is that i cannot think of a structure of a relational database for that.
i created it on mongodb and my structure was like that:
{
user: 'name',
etc...
tokens: [{
token: 'asdasijdoaisjd',
token: 'sodjio2n'
}]
}
so yeah... everytime a user logins in a new token gets added to the db and when he logs out from one place, one token gets deleted.
how can i create something similar in a relational database?

there is two ways to do that
add a column in your users table called tokens for example and save all of the tokens as JSON data
[Recomended] make a new table called users_tokens and make a relation of on to many between the user to tokens table and in the users_tokens table you will add a column called user_id to easily get all tokens that belong to the user
At last, you can read about how to implement one-to-many relation with sequelize here

Related

Vue + Firebase get all users with custom claim

I have a custom claim "admin" attached to each user, carrying a boolean.
Now, in my frontend i am trying to generate a list of all admins.
For that i need to access all users who have said custom claim set to "true" and put them in an array, which i can then generate the list from.
The array should just look like the following:
const admins = ref([
{
uid: *uid of admin1*,
name: *name of admin1*,
},
{
uid: *uid of admin2*,
name: *name of admin2*,
},
...
])
So the following problems arise:
How do i access all users with said custom claim set to true, so that i can loop over them and populate my array?
Is this a case for a cloud function, so that it can not be manipulated?
I tried reading this Firebase documentation, however i could not make sense of it.
How do i access all users with said custom claim set to true, so that i can loop over them and populate my array?
There is no direct way to query users based on custom claims.
Is this a case for a cloud function?
Yes, you would have to list all users as in the documentation that you've shared and check for custom claims for each user separately.
It might be best to use a database like Firestore or Realtime Database and maintain a collection of all admins. Make sure this cannot be updated from client side directly using security rules.

Getting data from foreign key of other table - TypeOrm(Mysql)

I am using nestjs and typeorm (Mysql). I have these tables users, orders and invoices.
Now invoices table has a foreign key linking to orders table and orders table links to user table.
Now when i am fetching invoices , i want to query user table , but i dont have foreign key for user table instead i have for order table and order table has foreign key for user table.
Is there any way to query user table when fetching invoice data ?
I tried the below code
const query = this.createQueryBuilder('invoice');
query.innerJoinAndSelect('invoice.order', 'order');
query.innerJoinAndSelect('order.user', 'user');
But it is giving this error
[Nest] 96607 - 11/09/2021, 11:08:49 [ExceptionsHandler] Relation with property path user in entity was not found.
It's more an advice than a solution.
TypeORM is not very intuitive and the documentation is not clear about it.
I reccomend you to change to a futuristic ORM, "PRISMA", the migration is very easy.
After installing it run this commands:
This command generates the schema automatically bassed on your database.
prisma introspect
This command applies the changes in your prisma schema.
prisma generate
After that youll have a pretty easy and accurate access to relationships.

Document database one to many - How to determine whether to reference or embed

I am relatively new to using mongoose and mongodb and trying to figure out what questions I should be asking myself when determining whether to create a new Schema and reference or embed by adding an array to an existing schema when there is a one to many relationship.
For example:
I have a User model. I need to keep track of User checkins (this will be a button the user presses on the UI to checking, it will call a POST route to my node api). I am debating on whether to embed an array of checkins to the User model or create a separate checkin Schema and reference User. I decided to create a checkin Schema that has a User reference by id. The reason for this is so I can query all checkins throughout the entire system easily (this is a requirement). I figured if I went the other direction and added an array of checkins to the User model (Schema), I would never be able to retrieve a master list of all checkins without looping through all of the Users in the system and compiling one. Additionally, now that I created a new Schema (model) I don't think I will be able to access a specific user's checkins from the User model, I would need to do a find on Checkins where userId=userId.
I am new to Mongo and Mongoose, so maybe there is a feature here that I might not be aware of.
The question is:
User (Schema)
checkins: [
{
...
},
],
or
User (Schema)
Checkin (Schema)
User

How to retrieve multiple users data based on userid in meteor js?

I have created a chat message functionality. The message stores the userid of sender and receiver. How can I get other details of the user just based on the userid?
Is creating a Meteor method the best way or I have to create publish/subscribe pattern for it.
I want to avoid sending all users data to client side.
I tried creating a meteor method but I don't think its the best approach.
Meteor.methods({
getUserInfoById: function (usrId) {
//console.log("BEGIN");
//console.log(usrId);
var user = Meteor.users.findOne(usrId);
//console.log(user);
//console.log("END");
return user;
}
});
Create a publisher (and also a subscriber) for the data about other users that you want a given user to see. You can restrict the fields returned using the {fields: ...} qualifier in the query.
This is a very common pattern. Using a method for this is an anti-pattern due to the extra round-trip delay for something you're likely to show quite often, i.e. another user's username or avatar.

Adding couchdb persistence to a socketio json feed in node

I'm currently researching how to add persistence to a realtime twitter json feed in node.
I've got my stream setup, it's broadcasting to the client, but how do i go about storing this data in a json database such as couchdb, so i can access the stores json when the client first visits the page?
I can't seem to get my head around couchdb.
var array = {
"tweet_id": tweet.id,
"screen_name": tweet.user.screen_name,
"text" : tweet.text,
"profile_image_url" : tweet.user.profile_image_url
};
db.saveDoc('tweet', strencode(array), function(er, ok) {
if (er) throw new Error(JSON.stringify(er));
util.puts('Saved my first doc to the couch!');
});
db.allDocs(function(er, doc) {
if (er) throw new Error(JSON.stringify(er));
//client.send(JSON.stringify(doc));
console.log(JSON.stringify(doc));
util.puts('Fetched my new doc from couch:');
});
These are the two snippets i'm using to try and save / retrieve tweet data. The array is one individual tweet, and needs to be saved to couch each time a new tweet is received.
I don't understand the id part of saveDoc - when i make it unique, db.allDocs only lists ID's and not the content of each doc in the database - and when it's not unique, it fails after the first db entry.
Can someone kindly explain the correct way to save and retrieve this type of json data to couchdb?
I basically want to to load the entire database when the client first views the page. (The database will have less than 100 entries)
Cheers.
You need to insert the documents in the database. You can do this by inserting the JSON that comes from the twitter API or you can insert one status at a time (for loop)
You should create a view that exposes that information. If you saved the JSON directly from Twitter you are going to need to emit several times in your map function
There operations (ingestion and querying) are not the same thing, so you should really do them at the different times in your program.
You should consider running a bg process (maybe in something as simple as a setInterval) that updates your database. Or you can use something like clarinet (http://github.com/dscape/clarinet) to parse the Twitter streaming API directly.
I'm the author of nano, and here is one of the tests that does most of what you need:
https://github.com/dscape/nano/blob/master/tests/view/query.js
For the actual query semantics and for you learn a bit more of how CouchDB works I would suggest you read:
http://guide.couchdb.org/editions/1/en/index.html
I you find it useful I would suggest you buy the book :)
If you want to use a module to interact with CouchDB I would suggest cradle or nano.
You can also use the default http module you find in Node.js to make requests to CouchDB. The down-side is that the default http module tends to be a little verbose. There are alternatives that give you an better API to deal with http requests. The request is really popular.
To get data you need to make a GET request to a view you can find more information here. If you want to create a document you have to use PUT request to your database.

Categories