Mr. BigglesWorth
Mr. BigglesWorth

Reputation: 1540

Looping through objects and adding them to Sequelize db

I have an array of objects that I like to put into SQL via Sequelize and I'm running into issues.

[ 
  { owner: false,
    id: '2342365',
    name: 'awrAPI' },
  { owner: false,
    id: '5675689699',
    name: 'TgatAPI' },
  { owner: true,
    id: '57456767',
    name: 'ytasyAPI' }
[

Currently the way i have it set up is through a simple for in.

    for( var key in guilds ) {
        Guild
        .findOrCreate({where: {primid: guilds[key].id}, defaults: {
            primid: guilds[key].id,
            name: guilds[key].name,
            owner: guilds[key].icon
        }})
        .spread(function(guild, created) {
            console.log(guild.get({
            plain: true
            }))
            console.log(created)
        })                      
    }

I assume this is wrong and was wondering if there is a better way to loop through my object and chain the findorcreates. Currently it goes through the first object, but then does not add any more. I've been looking into using Bluebird, but I'm not too familiar with using promises. Thoughts?

Upvotes: 1

Views: 1686

Answers (2)

Arausi Daniel
Arausi Daniel

Reputation: 191

An alternative would be to utilize squelize's bulkCreate model method for multiple records insertion. link to sequelize's bulkCreate docs

quick snippet here:

 const dataForInsertion = [ 
    {
      username:"daniel",
      currentORM:"Sequelize"
    },
    {
      username:"lekan",
      currentORM:"Mongoose"
    },
 ]

 Guild.bulkCreate(dataForInsertion)
     .then(()=>{})
     .catch(()=>{})

Upvotes: 2

Ricardo Seromenho
Ricardo Seromenho

Reputation: 529

var myData = [ 
  { 
    owner: false,
    id: '2342365',
    name: 'awrAPI' 
  },
  { 
    owner: false,
    id: '5675689699',
    name: 'TgatAPI'
  },
  { 
    owner: true,
    id: '57456767',
    name: 'ytasyAPI'
  }
];

Promise.all(myData.map(function(value) {
  // Do your thing
  return Guild.findOrCreate...
})).then(function() {
  // All is resolved do your next thing
})

Upvotes: 3

Related Questions