我们可以在sails 中的Create() 回调之后/之前更改属性值吗? [英] Can we change the value of attribute on after/before Create() callback in sails?

查看:27
本文介绍了我们可以在sails 中的Create() 回调之后/之前更改属性值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我必须用它的 id 填充模型的属性.例如...在用户模型中:

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

activation_link 的修改值也必须保存在数据库中.如何实现?

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

推荐答案

根据 thisthis 您的代码应该可以正常工作:您在 afterCreate 中的操作应该会改变结果对象.

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

更新

嗯...似乎第一个参数不是 Waterline 对象,尽管 文档内容.从技术上讲,您可以通过 id、更新和保存从 DB 重新获取记录,而不会产生大量开销(因为它应该只在创建时被调用一次).但我真的会避免在数据库中放入一个依赖于记录 ID 的字段:这样的数据库变得不可传输,因为您不能保证记录将具有相同的 ID.因此,解决方案要么是为这些激活链接使用一些令牌(干净的方式),要么只是将 activation_link 变成一个函数而不将其放入数据库中(简单的方法):

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

这篇关于我们可以在sails 中的Create() 回调之后/之前更改属性值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆