简体   繁体   中英

How to create route for particular user using postgreSQL and nodejs?

I am working on a nodejs project where I am using postgreSQL. The project is related to creating a timesheet for employers. I have already created routes for showing timesheet and project.

app.route(/api/timesheet)

Now, I want to create a user model for this project and want to add particular timesheet for particular user. That means, user with particular userid can only view timesheet information related to this user. I can do it with mongodb but I would like to do it with postgreSQL. Thank you in any advance for your help.

well, I've created users array where I have two users

const users = [
  {
      "id": "userId1",
      "email": "user1@mail.com",
      "password": "password"
  },
  {
      "id": "userId2",
      "email": "user2@mail.com",
      "password": "password2"
  }

];

then I created route as you wrote above

app.route('/api/timesheet')
  .get(function (req, res) {
    let id = req.params.id;

    let user = users.find(user => user.id = id);
    res.json(user);
  });

Routes does not varies, route is always same, just it brings different data according to what you pass as a parameter. if your GET request in query has "?userId=userId1" that will give you first object in response, so does if you pass second "userIs2", it will give you second one.


When I am using postgreSQL in nodejs project, I always do with sequelize


You can define user schema like that

module.exports = function(sequelize, DataTypes) {
      return sequelize.define('user', {
        email: Sequelize.STRING,
        password: Sequelize.STRING
      });
  }

and then you will call User.findById(id) and it will give you user specified with id of course

sequelize is a powerful library so you should look at the documentation before use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM