当我尝试更新数据库中的某个条目时,sequelize-Model.update()忽略传递给它的错误列名。假设我的表有“ id”和“ password”列,如果我将具有“ id”和“ pwd”的对象传递给更新函数,则“ pwd”将被忽略,而“ id”将被更新。
有没有一种方法可以通过序列检查是否将无效的列名传递给更新函数?
答案 0 :(得分:0)
您可以通过以下方式来实现此目的:通过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
}