28

I am working in nodejs project in that using sequelize for connecting mysql database. I am also using sequelize-values for getting raw data from Sequelize instances.

I have written below code

var Sequelize = require('sequelize');
require('sequelize-values')(Sequelize);
var sequelizeObj = new Sequelize('mysql://root:@localhost/database');

sequelizeObj.authenticate().then(function (errors) {
    console.log(errors)
});

sequelizeObj.query("SELECT * FROM `reports` WHERE `id` = 1200").then(function (result) {

    });

Now the table reports have only 1 record for id 1200, But the result gives two objects for same records, Means both records are same of id 1200.

[ [ { id: 1200,
  productivity_id: 9969,
  gross_percentage_points: 100 } ],
[ { id: 1200,
  productivity_id: 9969,
  gross_percentage_points: 100 } ] ]

Let me know what I am doing wrong?

4 Answers 4

69

The first object is the result object, the second is the metadata object (containing affected rows etc) - but in mysql, those two are equal.

Passing { type: Sequelize.QueryTypes.SELECT } as the second argument will give you a single result object (metadata object omitted

https://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0#changes-to-raw-query

1
  • const { QueryTypes } = require('sequelize'); var queryString = "SELECT id from users"; const userList = await Sequelize.query(queryString, { type: QueryTypes.SELECT });
    – rohit
    Apr 21, 2021 at 6:54
9

Try :

sequelizeObj.query("SELECT * FROM `reports` WHERE `id` = 1200", { type: Sequelize.QueryTypes.SELECT }).then(function (result) {
    });
3

Add { type: Sequelize.QueryTypes.SELECT } as the second argument, also remember to import Sequelize first.

-2

RESOLVED

sequelize.query("SELECT ...", { type: Sequelize.SELECT })
.then(result => {
    if (!result ) {
        res.status(404).send({ message: "Data Not found." });
    }

    res.status(200).send(result[0]);

})
.catch(err => {
    res.status(500).send({ message: err.message });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.