【问题标题】:How to exclude createdAT and updatedAt from ALL Queries in Sequelize?如何从 Sequelize 的所有查询中排除 createdAT 和 updatedAt?
【发布时间】:2021-04-12 11:30:13
【问题描述】:

我正在使用 Node 14 和 Sequelize 对现有 Postgres 数据库进行建模。

已经创建的表格没有 createdAt neighter updatedAt Colums 所以我想指示我的 Sequelize 永远不要尝试选择、插入或更新这些属性。

所以我尝试了

const sequelize = new Sequelize (
  config.database, 
  config.username, 
  config.password, 
  config.params,
  { define: {
     defaultScope: {
      attributes: { exclude: ['createdAt', 'updatedAt'] }
     },
     timestamps: false 
  }
})  

但即使这样......我的findAll()坚持选择createdAtupdatedAt

我错过了什么?

【问题讨论】:

  • 您是否考虑过在模型级别这样做?
  • 是的......事实上在模型作品中......但这不是一种全球方式吗?提前致谢,

标签: javascript node.js sequelize.js


【解决方案1】:

根据我的研究,你所拥有的应该是可行的,但正如我们所知,编程有时会很有趣。 :(

考虑尝试以下选项:

  • 使用beforeFind钩子方法
  • 添加范围以排除 createdAtupdatedAt 属性,就像在 this guide 中教导的那样

选项一示例

const sequelize = new Sequelize (
  config.database, 
  config.username, 
  config.password, 
  config.params,
  { 
    define: {
      hooks: {
        beforeFind: (model) => {
           model.attributes = {}
           models.attributes.exclude: ['createdAt', 'updatedAt']
        }
      },
      timestamps: false 
  }
})

选项二示例

const sequelize = new Sequelize (
  config.database, 
  config.username, 
  config.password, 
  config.params,
  { define: {
     scopes: {
      excludeCreatedAtUpdateAt: {
        attributes: { exclude: ['createdAt', 'updatedAt'] }
      }
     },
     timestamps: false 
  }
})

// Then use it when making your queries like this
const data = await Model.scope('excludeCreatedAtUpdateAt').findAll(...)

【讨论】:

    猜你喜欢
    • 2018-10-08
    • 2019-07-19
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多