Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

modify query function in Sequelize

I’m learning "Sequelize".
I went through documentation and got this code somewhere else.

Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body).then(
    result => {
        res.status.json({data: result})
    }).catch(err => console.log(err))
}

but I want this in the below structure,

Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
    Model.create(req.body, function (result, err) {
        if (err) {
            console.log(err)
        }
        else {
            res.status.json({data: result})
        }
    });
}

I tried this,.it didn’t send the response. But inserted the data correctly to db.
How to get the response in this case.?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The Model.create method returns a Promise, and does not have a callback parameter.
So you either handle the Promise with then:

module.exports.creareSalesman = (req, res, next) => {
  Model.create(req.body)
    .then((result) => {
      res.status.json({ data: result });
    })
    .catch((err) => console.log(err));
};

Or use async await:

module.exports.creareSalesman = async (req, res, next) => {
    try {
      const result = await Model.create(req.body);
      res.status.json({ data: result });
    } catch (err) {
      console.log(err);
    }
  };  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading