2017-04-13 656 views
3

我是Sequelize初學者。 我想oAuth使用Twitter或Facebook進行身份驗證,並希望將用戶信息保存在數據庫中。 但是,如果在多個站點上進行oAuth身份驗證,則存在如下問題:在數據庫中註冊的用戶ID等信息將與其他站點重複。 爲了避免這種情況,我希望僅在指定的用戶標識不存在於數據庫中時才執行更新數據庫的過程。 我知道我們可以使用sequelize的findOrCreate來做這樣的處理,但我不知道如何使用findOrCreate。 我知道如何使用upsert,並且想要像下面的upsert描述那樣進行findOrCreate。但是,我們想要執行條件分支,如if(userid!=「○○○」& & username!=「○○○」)。如何在Sequelize中使用findOrCreate

 User.upsert 
     ({ 
      userid: profile.id, 
      username: profile.username, 
      accountid: c+1 
     }).then 
     (() => { 
      done(null, profile); 
     }); 

我該怎麼辦?

回答

5
// remember to use transaction as you are not sure 
// whether user is already present in DB or not (and you might end up creating the user - a write operation on DB) 
models.sequelize.transaction(function(t){ 
    return models.users.findOrCreate({ 
    where: { 
     userId: profiile.userId, 
     name:  profiile.name 
    }, 
    transaction: t 
    }) 
    // necessary to use spread to find out if user was found or created 
    .spread(function(userResult, created){ 
    // this userId was either created or found depending upon whether the argment 'created' is true or false 
    // do something with this user now 
    if (created){ 
     // some logic 
    } 
    else { 
     // some other logic 
    }  
    }); // end spread 
}) // end transaction