Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize TypeError build.save is not a function

I have some jQuery logic setup where users can submit multiple field values, which should be created as individual records in my database. My former solution to doing this was to map my values to a variable that is then used with the .bulkCreate method, but I was unaware that MYSQL does not support auto-incrementing fields with this method. As a result I decided to take my logic and instead create a for loop with the .create method. Unfortunately I receive this error message: TypeError: this.build(...).save is not a function at the line models.DiscoverySource.create(sources). Why does this message appear when I'm not using the build method?

.post(function(req, res){
        console.log(req.body.discoverySource);
    var sources = _.map(req.body.discoverySource, function (source) {
        return {
             discoverySource: source,
             organizationId: req.body.organizationId
        };
    });
    console.log("These are the" + sources); //outputs "These are the [object Object],[object Object], [object Object]
    console.log(sources[0].discoverySource); //outputs correctly first value 
    console.log(sources[0].organizationId); //outputs correctly the first value

    for (i=0; i < sources.length; i++){
        models.DiscoverySource.create(sources)
        .then(function(){
        return models.DiscoverySource.findAll();
        }).then(function(discoverySource){
        console.log(discoverySource);
        res.redirect('/app');
        }).catch(function(error){
        res.send(error);
        console.log('Error during Post: ' + error);
        });
    }
});
like image 964
cphill Avatar asked Oct 18 '22 12:10

cphill


1 Answers

The create method cannot accept an array of objects. If you need the ID's, and need to wait until all the object are created, you will need to wait for all the individual create promises :

var promises = sources.map(source => models.DiscoverySource.create(source));

Promise.all(promises)
.then(() => models.DiscoverySource.findAll())
.then(discoverySource => {
  console.log(discoverySource);
  res.redirect('/app');
}).catch(error => {
  res.send(error);
  console.log('Error during Post: ' + error);
});
like image 185
AvnerSo Avatar answered Oct 22 '22 02:10

AvnerSo