从预保存挂钩和更新属性

时间:2016-11-19 07:57:23

标签: javascript node.js mongoose

我想从我的预保存挂钩中调用一个函数来更新正在保存/更新的实例中的属性。我不想在架构方法中再次调用save()。

另外,下面只是一个例子,但我有一些shema方法需要很长时间,而且我不想将它们包含在预保存挂钩中。

UserSchema.pre('save', function(next) {
  const user = this;
  ...
  if (user.isModified('something')) {
    user.checkSomething();
  }
  ...
  next();
});

UserSchema.method.checkSomething() = function() {
  const user = this;

  if(user.something > 5) {
    // Any way to update the below property without calling save() again?
    user.somethingElse = true;
  }
}

一旦函数返回,似乎变化不是永久性的。

谢谢。

1 个答案:

答案 0 :(得分:0)

除了示例代码中的拼写错误之外,我唯一的猜测是checkSomething函数具有异步操作,pre-save中间件同步运行。

// include `done` for async operation
UserSchema.pre('save', function(next, done) {
  const user = this;

  next();

  if (user.isModified('something')) {
    // Assuming this is asynchronous
    user.checkSomething(done);
  } else {
    done();
  }
});

UserSchema.method('checkSomething', checkSomething);

// Async function
function checkSomething(cb) {
  const user = this;

  if (user.something > 5) {
    doSomethingAsync(function(err, res) {
      if (err) {
        return cb(err);
      }

      user.somethingElse = res;
      cb();
    });
  } else {
    cb();
  }
}

注意:如果您要修改实例值,我建议您在pre-validate步骤中执行此操作,以便模型可以在保存之前验证修改后的值。

UserSchema.pre('validate', function(next) {
  const user = this;

  if (user.isModified('something')) {
    // Assuming this is synchronous
    user.checkSomething();
  }

  next();
});

UserSchema.method('checkSomething', checkSomething);

function checkSomething() {
  const user = this;

  if (user.something > 5) {
    user.somethingElse = true;
  }
}
相关问题