【问题标题】:SailsJS: can not create Model in beforeCreateSailsJS:无法在 beforeCreate 中创建模型
【发布时间】:2016-07-26 10:42:17
【问题描述】:

我使用 SailsJS (v0.12.3),我想在创建用户资料之前创建一个用户。我的问题是用户创建成功,但 UserProfile 没有。

这是我的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 之前创建用户模型?

谢谢!

【问题讨论】:

    标签: node.js sails.js


    【解决方案1】:

    稍后阅读模型操作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
        // ...
    }
    

    感谢阅读。希望这对其他人有帮助!

    【讨论】:

    • 确保在使用生命周期回调时会回调。
    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2015-10-04
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多