如何访问模型方法?

时间:2016-06-27 10:07:04

标签: node.js sequelize.js

我的用户看起来像这样:

User = sequelize.define('user', {},{
    classMethods: {
        register: (params) => {
            var user = User.build(),
                fbprofile = userAttributes.build({name: 'fbprofile', value: params.fbprofile}),
                afterAllResolved = (results) =>
                {
                    return results[0]
                        .addUserAttributes([
                            results[1]
                        ]);
                };

            user.save();
            fbprofile.save();

            return sequelize.Promise.all([user, fbprofile])
                .then(afterAllResolved);

        },
        show: () => {
            this.getUserAttributes()
                .then((attributes) => {
                    return {
                        user: user,
                        attributes: attributes
                    };
                });
        }
        ...

我尝试这样做:

app.get('/user/create',
    (req, res) => {
        User.register(req.query)
            .then((user) => {
                console.log(user.show);
                res.json('done');
            });
    }

由于某种原因,user.show未定义,为什么?我希望它是一种方法。 我是否可以使用"这个"在show中引用对象的当前实例?

1 个答案:

答案 0 :(得分:3)

我注意到的一些事情:

user.save();
fbprofile.save();

return sequelize.Promise.all([user, fbprofile])
  .then(afterAllResolved);

这似乎不正确:userfbprofile都是模型实例,而不是承诺。我想你想要这个:

return sequelize.Promise.all([ user.save(), fbprofile.save() ])
  .then(afterAllResolved);

其次,您将show声明为类方法;换句话说,您可以将其用作User.show()用作user.show()。为此,您需要将其声明为实例方法:

instanceMethods : {
  show: function() {
    return this.getUserAttributes() // return this promise!
      .then((attributes) => {
        return {
          user       : this, // `user` isn't defined here, I assume it's `this`
          attributes : attributes
        };
      });
  }
}