Search code examples
node.jsexpressmongoosepassport.jspassport-jwt

Express.js: user access just the data created by them


Im struggling with Express.js and MongoDB. I already configured passport login and passport-jwt, and it works just fine, but now I have a problem. For example I have two users and one table, and I want when the first user login in the application, they have access the data created by them. What is the best solution for this? Create one table per user? Help me out and I appreciate your help!


Solution

  • you can update your schema of data that will be stored inside table, by adding:

    owner {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
    }
    

    while user will be the name of modeling that created as users database, so every data inside that table will have id of its owner, and every time you want to display that data or send to the user, you can check if id of the owner of that data equals to the id of the user already login, and depend on that you can display the data of table or not.
    and the id of the user will be stored inside req.user._id which will be created by passport package.