const db = require('../db.js');
const languageToId = require('../seed/languages.js').languageToId;
const levelToId = require('../seed/levels.js').levelToId;
const LanguagesLevels = require('../models/languageLevelModel.js');
const Users = require('../models/userModel.js');

module.exports = (type, userId, languageLevels) => ( // languageLevels is an array of tuples in the form of [language, level]
  db.query(`
    DELETE FROM users_languages_levels 
      WHERE user_id = '${userId}'
  `)
  .spread(results => results)
  .then(() => (
    Users.findById(userId)
      .then(user => {
        const languageLevelQueries = languageLevels.map(languageLevel => (
          LanguagesLevels.findOrCreate({
            where: {
              language_id: languageToId[languageLevel[0]],
              level_id: levelToId[languageLevel[1]],
            },
          })
          .spread(results => results)
        ));
        return Promise.all(languageLevelQueries)
          .then(lls => {
            const addQueries = lls.map(ll => (
              user.addLanguagesLevels(ll, { type })
            ));
            return Promise.all(addQueries);
          });
      })
  ))
);

@@ -489,58 +489,92 @@
   %60)
-%0A  .spread(results =%3E results)%0A  .then(() =%3E (%0A   
+ // delete existing associations between user and any languageLevels%0A  .spread(() =%3E
  Use
@@ -592,21 +592,18 @@
 (userId)
+)
 %0A
-    
   .then(
@@ -612,28 +612,24 @@
 er =%3E %7B%0A    
-  
-  
 const langua
@@ -689,20 +689,16 @@
 (%0A      
-    
 Language
@@ -728,20 +728,16 @@
         
-  
-  
 where: %7B
@@ -737,20 +737,16 @@
 here: %7B%0A
-    
         
@@ -802,20 +802,16 @@
         
- 
-   
 level_id
@@ -849,20 +849,16 @@
         
-    
 %7D,%0A     
@@ -862,19 +862,11 @@
     
-  
-  
 %7D)%0A
-    
     
@@ -881,17 +881,16 @@
 d(result
-s
  =%3E resu
@@ -895,27 +895,87 @@
 sult
-s)%0A        ));
+) // each result is an instance of the LanguagesLevels sequelize model
 %0A    
+));%0A
     
@@ -1015,20 +1015,16 @@
 ueries)%0A
-    
       .t
@@ -1044,20 +1044,16 @@
         
-    
 const ad
@@ -1089,20 +1089,16 @@
         
-    
 user.add
@@ -1118,16 +1118,32 @@
 ls(ll, %7B
+ offer_or_learn:
  type %7D)
@@ -1151,20 +1151,16 @@
         
-    
 ));%0A    
@@ -1163,20 +1163,16 @@
         
-  
-  
 return P
@@ -1205,28 +1205,15 @@
     
-    
 %7D);%0A  
-    %7D)%0A  )
+%7D
 )%0A);

Improve promise readability