Link to home
Start Free TrialLog in
Avatar of Omar Martin
Omar MartinFlag for United States of America

asked on

How to select a specific record by Id in a database using sequelize?

I would like to select a record from a mysql database by "id" using sequelize.  I currently can do it with a mysql query and it works but I am receiving a null result when attempting to do it in sequelize.  Here is the query in my mysql which works and the query in sequelize which does not work. What am I doing wrong with the syntax in the sequelize version?




``````````````````````````````````````````````````````````````````````````````
        (1)

        router.get("/station/number/:id", (req, res) => {
      db.query(
            "SELECT * FROM stores WHERE id = ?",
            [req.params.id],
            (err, rows, fields) => {
                  if (!err) res.send(rows);
                  else console.log(err);
            }
      );
});


       (2)
 
      router.get("/station/number/:id", (req, res) =>

      Store.findOne ({
      where: {id:'?'}})
      .then(data=>{
     res.send({stores:data})
      })
     .catch(err => console.log(err)));
Avatar of David Favor
David Favor
Flag of United States of America image

The sequelize seems to be rarely used.

If you get no comments here, contact the sequelize developer for assistance.
Avatar of Omar Martin

ASKER

What do most developers use instead of sequelize?

I like the idea of being able to use the same code across various databases..ie. Mysql, Firebase, MariaDb, Postgre....etc. you can plug in quickly.
ASKER CERTIFIED SOLUTION
Avatar of Jim Riddles
Jim Riddles
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Jim:

Yes.....thank you.....I will review it.....are you handy with sequelize, I could use your help.
Jim.....Here is a solution I tracked down.....

router.get("/station/number/:id", (req, res) =>

Store.findByPk(req.params.id)
   .then(stores =>{
     res.json(stores);
   })
   .catch(err => {
     console.log(err);
     res.status(500).json({msg: "error", details:err});
   }));
It use to be .......findById..........but version 5 has been changed that to .......findByPk
I have a passing familiarity with sequelize, but would definitely call myself an Expert on the subject.  Reading the documentation for findOne is where I noticed the issue.  findByPk is probably the best solution for your specific request.  Did my suggestion not work?
Yes...it worked.......I will mark it as the solution however, I have other routes written in sql query which I would like help with to convert them to sequelize......can I count on your assistance Sir?
I'll do what I can.  Send me a direct message with a link to the questions you create and I will see how I can assist you.
Thanks...
Thank you David and Jim for your assistance....It was greatly appreciated.