Vunb
Vunb

Reputation: 494

SailsJS: can not create Model in beforeCreate

I use SailsJS (v0.12.3) and i want to create a User before it's profile created. My problem is the User is created successfully, but the UserProfile did not.

This is my UserProfile model:

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);
    });
}

The console output:

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

I can see message Creating user login ... is printed, but i can not see the log message Creating user done ... and ABC error.

The result: in database i got the user created but userProfile did not.

How can i create User model before UserProfile create correctly ?

Thank you!

Upvotes: 2

Views: 166

Answers (1)

Vunb
Vunb

Reputation: 494

After a while read about Model actions Lifecycle callbacks. I find my code did not call back function afterCreatethat i defined in the User model. So, i do remove the function afterCreate, then it works.

// ./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
    // ...
}

Thank for reading. Hope this help others !!

Upvotes: 3

Related Questions