获取 Sails 的 Waterline beforeUpdate 钩子内的当前值

Tal*_*son 5 javascript node.js sails.js waterline

在 Sails 的 Waternline 中,我需要能够将以前的值与新值进行比较,并在某些条件下分配一个新属性。例如:

beforeUpdate: function(newValues, callback) {
   if(/* currentValues */.age > newValues.age) {
     newValues.permission = false;
   }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能访问currentValues?

Yan*_*and 3

我不确定这是最好的解决方案,但您可以通过执行一个简单的findOne请求来获取当前记录:

beforeUpdate: function(newValues, callback) {
  Model
    .findOne(newValues.id)
    .exec(function (err, currentValues) {
      // Handle errors
      // ...

      if(currentValues.age > newValues.age) {
        newValues.permission = false;
      }

      return callback();
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您没有传递“id”进行更新,或者您根据条件而不是“id”更新多个记录,则此操作将不起作用。 (3认同)