0

Using Express in server side and Axios to send res calls. While trying to save data into MySql database, I am getting below error in console: Using sequelize.js for model/schema creation.

Error:

(node:23364) UnhandledPromiseRejectionWarning: TypeError: this.build(...).save is not a function
    at Function.create (C:\Main\Work\devchoice\node_modules\sequelize\lib\model.js:2228:8)
    at CsvParser.<anonymous> (C:\Main\Work\devchoice\src\server.js:289:60)
    at CsvParser.emit (events.js:315:20)
    at endReadableNT (_stream_readable.js:1220:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:23364) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with .catch()

server.js

const manageNomineesSchema = require('./server/models/managenominees');
const ManageNomineesModel  = manageNomineesSchema(sequelize, DataTypes);

    app.post('/service/managenominees', upload.single('file'), async (req, res, next) => {
      try {
        if(req.file){
          let filePath = req.file.path;
          fs.createReadStream(filePath)
              .pipe(csv())
              .on('data', (data) => results.push(data))
              .on('end', async () => {
                console.log(results);
                let manageNominees = await ManageNomineesModel.create(results);
                //res.status(200).send(manageNominees);
                res.status(200).json({ message: "Nominees inserted successfully !"});
              });
          }
    
      } catch (e) {
        res.status(500).json({ fail: e.message });
      }
    });

enter image description here

enter image description here

1 Answer 1

1

.create takes an object as an argument to create 1 instance, however, you are passing an array of objects.

If you would like to insert everything in the array, use .bulkCreate.

ref: https://sequelize.org/master/class/lib/model.js~Model.html#static-method-bulkCreate

Sign up to request clarification or add additional context in comments.

9 Comments

Thank you very much Emma, it worked out well, upvoted and accepted!
bulkCreate can be also used to update. stackoverflow.com/a/54900639/2956135
I have tried the same way, but no luck yet, it’s inserting the same records again.
Have you added PK value to the object in array and use updateOnDuplicate?
I have tried as per the example:’ await ManageNomineesModel.bulkCreate(allNominees,{ updateOnDuplicate: ["name"] })’
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.