Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize - Bulk create from array

I have an array of items and need to create them to DB.

I need to check each insert if it success so insert to new array (results) the item + success = true as a json.

If not succeed to create - insert to the same array before (results) the item + success = false.

Here's the code:

create_cards: function (filter_id, is_filter, cards) {
    var result = [];
    var curr_card = null;
    for (var card in cards) {
        curr_card = this.create( {
            filter_id: filter_id,
            template: card.template,
            state: card.state,
            question_id: card.question_id || -1,
            answers: card.answers || -1,
            description: card.description || -1,
            correct_answer: card.correct_answer || -1
        }).then(function(card) {
            result.push({card: JSON.stringify(card.dataValues), success: true})
        },function(err) {
            result.push({card: card.dataValues, success: false})
        });
    }
    return results;
}

Now, 2 questions:

  1. There is 'return result' after the loop is over, but i get empty array.. How should i do bulk create AND after each create, to make sure if the creation succeed?

  2. How should i get the card in the error function? i get only 'err' as variable to the reject function.

Thanks!

like image 905
Zvi Avatar asked Aug 01 '16 15:08

Zvi


1 Answers

create_cards: function(filter_id, is_filter, cards) {
  var result = [];

  var promises = cards.map(function(card) {
    return this.create({
        filter_id: filter_id,
        template: card.template,
        state: card.state,
        question_id: card.question_id || -1,
        answers: card.answers || -1,
        description: card.description || -1,
        correct_answer: card.correct_answer || -1
      })
      .then(function() {
        result.push({
          card: card,
          success: true
        });
      })
      .catch(function(err) {
        result.push({
          card: card,
          success: false
        });
        return Promise.resolve();
      });
  });

  return Promise.all(promises)
    .then(function() {
      return Promise.resolve(result);
    });
}
like image 133
nika.interisti Avatar answered Oct 18 '22 16:10

nika.interisti