0

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?

nishi
  • 512
  • 1
  • 4
  • 19

1 Answers1

2

there is two ways to do that

  1. add a column in your users table called tokens for example and save all of the tokens as JSON data

  2. [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

enter image description here

At last, you can read about how to implement one-to-many relation with sequelize here

Joseph
  • 5,644
  • 3
  • 18
  • 44
  • 2
    I'd prefer point 2 because tokens are changed much more frequently comparing to a user itself. – Anatoly Aug 22 '20 at 16:31
  • 1
    yah i agree with you it would be more easily to manage and edit – Joseph Aug 22 '20 at 16:33
  • ok i made both, using one-to-many and not using it. And i dont understand whats the point of using it. Cuz i can set the userId of the tokens to be the userid whenever i create a new token. So if i wanna manage the user tokens i manage via the userid. whats the point of creating the one-to-many relation? – nishi Aug 22 '20 at 18:29
  • 1
    @nishi when you create a column `userid` in another table this called one-to-many but when you create a foreign key it will add more validation layer in case if you forget to add it – Joseph Aug 22 '20 at 19:59
  • alright ive done that. But, it means that it is not super required to explicitly do: "Tokens.hasMany(User); User.belongsTo(Tokens)" ? – nishi Aug 22 '20 at 20:39
  • in `sequelize` it will add for you more functionality that will help you with it's powerfull ORM system. – Joseph Aug 22 '20 at 20:52
  • 1
    If you will not wish to get a user long with his/her tokens then you don't need to add association User.hasMany(Tokens) as well as you don't need to add Tokens.belongsTo(User) if you don't want to load a user of a given token. – Anatoly Aug 22 '20 at 23:06