Sequelize.js 如何更新Sequelize模型(不包括字段)
查看Sequelize文档,我找到了如何指定我想要更新的字段,但我想指定我不想要更新的字段 诸如此类:Sequelize.js 如何更新Sequelize模型(不包括字段),sequelize.js,Sequelize.js,查看Sequelize文档,我找到了如何指定我想要更新的字段,但我想指定我不想要更新的字段 诸如此类: Model.update(,{excludeFields:['id']}) 有什么方法可以做到这一点吗?也许这也适用于更新 Model.findAll({ attributes: { exclude: ['baz'] } }); 当我遇到这个问题时,我没有在sequelize docs中找到解决这个问题的方法,但我通过以下方式解决了它: Model.findOne() .then(i
Model.update(,{excludeFields:['id']})
有什么方法可以做到这一点吗?也许这也适用于更新
Model.findAll({
attributes: { exclude: ['baz'] }
});
当我遇到这个问题时,我没有在sequelize docs中找到解决这个问题的方法,但我通过以下方式解决了它:
Model.findOne()
.then(instance => {
const fields = instance.attributes.filter(attribute => {
return !['foo'].includes(attribute);
});
return instance.update(data, { fields });
});
TL;DR
获取所有字段,然后排除不需要的字段
const fieldsToExclude = ['password', 'sensitive_info', 'attribute_not_allowed_due_to_user_role']
const myFields = Object.keys(MyModel.rawAttributes).filter( s => !fildsToExclude.includes(s))
MyModel.update(newValue, {fields: myFields})
如果你问(你应该问)我从哪里得到这个,它不在文件中!
继续阅读
一些细节虽然我很喜欢Sequelize,但我承认他们的参考资料有时缺乏一些信息 e、 g.
findByPk
内部调用findOne
,这一事实在内部调用了findAll
,这意味着传递给findAll
的选项
对象也适用于findOne
和findByPk
不幸的是,update
方法不能处理与find*
函数族相同的选项
对象。
下面是update
如何处理对象的属性
// Remove values that are not in the options.fields
if (options.fields && options.fields instanceof Array) {
for (const key of Object.keys(values)) {
if (options.fields.indexOf(key) < 0) {
delete values[key];
}
}
} else {
const updatedAtAttr = this._timestampAttributes.updatedAt;
options.fields = _.intersection(Object.keys(values), Object.keys(this.tableAttributes));
if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) === -1) {
options.fields.push(updatedAtAttr);
}
}
这就是“排除”逻辑发生的地方
HTH如果要排除的属性数很小,比如2个或1个,并且只想不允许更新某个属性,最简单的解决方案是从更改对象中删除对象属性
if (model) {
delete model.password;
delete model.sensitive_info;
}
对不起,那是不对的。虽然这适用于findAll
,但不适用于update
我需要在beforeUpdate
钩子中使用此行为,并且由于钩子中只有实例,因此将要排除的字段设置为undefined
具有排除它的效果。
if (model) {
delete model.password;
delete model.sensitive_info;
}