Himmators Himmators - 5 months ago 11
Node.js Question

How to access model-method?

I have a user that looks like this:

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


And I try to do this:

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


For some reason user.show is undefined, why? I expect it to be a method.
Will i be able to use "this" in show to reference the current instance of the object?

Answer

A few things that I noticed:

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

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

This doesn't seem right: both user and fbprofile are model instances, not promises. I think you want this:

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

Secondly, you're declaring show as a class method; in other words, you can use it as User.show() but not as user.show(). For that, you need to declare it as an instance method:

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