sequelize更新忽略无效的列名

yrefmtwq  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(315)

当我尝试更新数据库中的某个条目时,sequelize-model.update()会忽略传递给它的错误列名。假设我的表有'id'和'password'列,如果我将一个具有'id'和'pwd'的对象传递给update函数,那么'pwd'将被忽略,而'id'将被更新。
有没有办法通过sequelize检查是否有无效的列名被传递给update函数?

xlpyo6sf

xlpyo6sf1#

您可以通过向模型中添加自定义示例函数来实现这一点 prototype 能够访问 this 放弃 this.update() 如果你的支票通过。

const MyModel = sequelize.define(
  'table_name',
  { ...columns },
  { ...options },
);
MyModel.prototype.validatedUpdate = async (updates, options) => {
  // get a list of all the column names from the attributes, this will include VIRTUAL, but you could filter first.
  const columnNames = Object.keys(MyModel.attributes);
  // the keys from the updates we are trying to make
  const updateNames = Object.keys(updates);

  // check to see if each of the updates exists in the list of attributes
  updateNames.forEach(updateName => {
    // throw an Error if we can't find one.
    if (!columNames.some((columnName) => columnName == updateName)) {
      throw new Error(`The field ${updateName} does not exist.`);
    }
  });

  // pass it along to the normal update() chain
  return this.update(updates, options);
}
module.exports = MyModel;

然后像这样使用:

try {
   const myInstance = await MyModel.findById(someId);
   await myInstance.validatedUpdate({ fake: 'field' });
} catch(err) {
   console.log(err); // field does not exist
}

相关问题