szewah
szewah

Reputation: 147

Sequelize findByPk returns null

I want to find a user by his/her id. I used sequelize findByPk() and the response came back as null whereas I got all the data using findAll(). So the connection to the database is there.

controllers.js

module.exports = {
    findAll: function(req, res) {
        User.findAll()
        .then(user => {
            res.json(user);
        })
        .catch((err) => res.status(422).json(err));
    },
    findByPk: function(req, res) {
        User.findByPk(req.params.id)
        .then(user => {
            res.json(user)
        })
        .catch((err) => console.log(err));
    }
};


routes.js

router.get('/all', userController.findAll);
router.get('/oneUser', userController.findByPk);

Upvotes: 1

Views: 5365

Answers (3)

dwweb0309
dwweb0309

Reputation: 104

I also had the same problem and spend hours to resolve the issue.

Using findByPk is the best practice if we are searching one item from primary key. findOne or others are not good fit for this case

I finally fixed by adding id field into the model with primaryKey attribute.

id: {
  allowNull: false,
  type: DataTypes.INTEGER,
  primaryKey: true
}

By default, id field is added to the model, but if the model has more than one field that is primary keyed, then we have to manually add id field as above.

Upvotes: 2

Elodie Jean
Elodie Jean

Reputation: 3

I had the same problem when I try my request on postman but then I console.log the id that I tried to have and it works so my request was good but I forgot a setting on postman test with adding id and number id here :

Postman setting FindById

Upvotes: -1

KenOn10
KenOn10

Reputation: 1968

Are you certain that req.params.id contains a valid PK? Does findByPk work if you test with a hard-coded value, e.g. User.findByPk(1).then.... ?

If nothing else, you could use a where clause so you need not iterate:

findByPk: function(req, res) {
   User.findAll({where : {id : req.params.id }})  /* assumes pk is 'id' field */
   .then(user => {
      res.json(user)
   })
.catch((err) => console.log(err));
}

Upvotes: 2

Related Questions