Can we change the value of attribute on after/before Create() callback in sails?

China☆狼群 提交于 2019-12-10 19:57:41

问题


I have a scenario where I have to populate attribute of model with its id. For eg.. In User model:

module.exports = {
attributes: {
    activation_link: "string"
},
 afterCreate: function(value, cb) {
    value.activation_link = "localhost:1337/user/action/"+ value.id;
    cb();
}

The activation_link's modified value has to saved in the database too. How can that be achieved?


回答1:


According to this and this your code should actually work: your manipulations in afterCreate are supposed to mutate the resulting object.

UPDATE

Hmm... Seems like the first parameter is not a Waterline object, despite of what the documentation says. Technically, you can refetch the record from DB by id, update and save without a lot of overhead (since it's supposed to be only called once upon creation). But I would really avoid putting in the DB a field that depends on a record id: such DB becomes untransportable, since you can't guarantee that the records will have the same ids. So, the solution would be either use some tokens for these activation links (the clean way) or just make activation_link a function without putting it in the DB (the simple way):

module.exports = {
  attributes: {
  },
  activation_link: function() {
    if (!this.id)
      return false;

    return 'localhost:1337/user/action/' + this.id;
  }
}



回答2:


Change from afterCreate to beforeCreate (sails -v 0.12.14)

beforeCreate: function (attrs, cb) {
    attrs.createdAt = moment().format()
    attrs.updatedAt = attrs.createdAt
    return cb();
  },

beforeUpdate: function (attrs, cb) {
    attrs.updatedAt = moment().format()
    return cb();
  }

document here offical sails model lifecycle



来源:https://stackoverflow.com/questions/24059949/can-we-change-the-value-of-attribute-on-after-before-create-callback-in-sails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!