如何根据其他模型数据验证字段

时间:2019-01-31 12:37:26

标签: mysql node.js validation express sequelize.js

我正在尝试通过另一个模型基于存储在数据库中的信息来验证日期字段。

当我测试api时,验证会正确抛出异常,但但是,插入会在此异常之前发生。也就是说,它不会阻止插入数据库。我哪里出问题了?

这是我的验证功能:

<ul>
{% for q, opts in in quesBank.items %}
    <li>
        Q : {{ q  }}
        <ol> 
        {% for opt in opts %}
          <li>{{opt}}</li>        
        {% endfor %}
        </ol>
    </li>
   {% endfor %} 
</ul>

这是结果:

module.exports = (sequelize, DataTypes) => {
  const Step = sequelize.define('Step', {
  ...
  resultDate: {
    type: DataTypes.DATE,
    validate: {
      isEven(value){
        sequelize.models.Call
          .findById(this.call_id)
          .then(call => {
            if(value >= call.endingDate) throw new Error('Error message here!');
          });
  ...

很明显,最初的SELECT是要执行验证,但是,在退出验证并引发异常之前,API会插入数据库中并已成功返回!

如何在插入之前要求模型等待所有验证?

1 个答案:

答案 0 :(得分:1)

通过更改自定义验证器Arity(第二个参数是回调),可以将其更改为异步处理程序。因此您的代码应如下所示:

DECLARE
   CREATE CURSOR my_cursor IS
      SELECT division_id, name AS worker, salary
         FROM worker
         ORDER BY division_id, salary desc;
   division_id NUMBER;
   row_count_per_id NUMBER;
BEGIN
   FOR my_rec IN my_cursor LOOP
      -- If first iteration then initialize variables
      IF (row_num = 0) THEN
         division_id := myRec.division_id;
         row_count_per_id := 1;
      END IF;

      -- row_num can't be 0 at this point
      IF (division_id = myRec.division_id) THEN
         IF (row_count_per_id < 3) THEN
            -- Print first record of the new division_id
            DBMS_OUTPUT.PUT_LINE('division_id = ' || myRec.division_id || 
                                 ', Worker = ' myRec.worker ||
                                 ', salary = ' myRec.salary;
            row_count_per_id := row_count_per_id + 1;
         END IF;
      ELSE
         -- division_id has changed from the previous row
         -- Add the first row of new division_id 
         division_id = myRec.division_id;
         row_count_per_id := 1;
         DBMS_OUTPUT.PUT_LINE('division_id = ' || myRec.division_id || 
                              ', Worker = ' myRec.worker ||
                              ', salary = ' myRec.salary;
      END IF;
   END LOOP;
END;