2016-07-26 36 views
2

我使用SailsJS(v0.12.3),並且我想在創建配置文件之前創建一個用戶。我的問題是用戶創建成功,但UserProfile沒有。SailsJS:無法在beforeCreate中創建模型

這是我UserProfile型號:

beforeCreate: function (userProfile, cb) { 
    // Creating user login 
    console.log("Creating user login: ", userProfile); 
    User.create({ 
     username: "abc", 
     password: "1234567890" 
    }).then(function (user) { 
     console.log("Creating user done: ", user) 
     userProfile.appUser = user.id; 
     userProfile.code = user.username; 
     cb(null, userProfile); 
    }).catch(function (err) { 
     console.log("ABC", err); 
     cb(err); 
    }); 
} 

控制檯輸出:

Creating user login: { firstName: 'Vu', 
    lastName: 'Bao', 
    gender: 1, 
    phoneNumber: '0987654321', 
    id: '29b1b37b-ca95-4fd0-8cf8-e35a25af4616', 
    code: '1469529082587', 
    isVerified: false, 
    totalVisit: 0 } 

我可以看到打印信息Creating user login ...,但我不能看到日誌消息Creating user done ...ABC錯誤。

結果:在數據庫中我創建了user,但是userProfile沒有。

如何在UserProfile創建之前創建用戶模型?

謝謝!

回答

3

經過一段時間閱讀關於型號動作Lifecycle callbacks。我發現我的代碼沒有回撥我在User模型中定義的功能afterCreate。所以,我確實刪除了功能afterCreate,然後才能正常工作。

// ./api/models/User.js 
afterCreate: function (user, cb) { 
    // i commented a lots in this function, but did not callback cb 
    // then i remove this method because I did not need it anymore 
    // ... 
} 

感謝您的閱讀。希望這可以幫助別人!

+1

確保您在使用生命週期回調的情況下會回撥。 – Vunb

+1

你能寫一個示例代碼嗎? –

+0

我用代碼示例更新了我的答案:) – Vunb