如何在 Sequelize 中进行查询?

How to do a query in Sequelize?

我有一个现有的 Postgres 数据库。通过 sequelize-auto,我为现有数据库生成了模型。例如,让我们看一下 tc_devices table (tc_devices.js):

const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
  return sequelize.define('tc_devices', {
    id: {
      autoIncrement: true,
      autoIncrementIdentity: true,
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING(128),
      allowNull: false
    },
    uniqueid: {
      type: DataTypes.STRING(128),
      allowNull: false,
      unique: "tc_devices_uniqueid_key"
    },
    lastupdate: {
      type: DataTypes.DATE,
      allowNull: true
    },
    positionid: {
      type: DataTypes.INTEGER,
      allowNull: true
    },
    groupid: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'tc_groups',
        key: 'id'
      }
    },
    attributes: {
      type: DataTypes.STRING(4000),
      allowNull: true
    },
    phone: {
      type: DataTypes.STRING(128),
      allowNull: true
    },
    model: {
      type: DataTypes.STRING(128),
      allowNull: true
    },
    contact: {
      type: DataTypes.STRING(512),
      allowNull: true
    },
    category: {
      type: DataTypes.STRING(128),
      allowNull: true
    },
    disabled: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: false
    }
  }, {
    sequelize,
    tableName: 'tc_devices',
    schema: 'public',
    timestamps: false,
    indexes: [
      {
        name: "tc_devices_pkey",
        unique: true,
        fields: [
          { name: "id" },
        ]
      },
      {
        name: "tc_devices_uniqueid_key",
        unique: true,
        fields: [
          { name: "uniqueid" },
        ]
      },
    ]
  });
};

database.js中,我连接到数据库:

const { Sequelize } = require('sequelize');

const sequelize = new Sequelize(database, user, password, {
    host,
    port,
    dialect: 'postgres',
    logging: false
  })

async function db_connection(){  
try{
  await sequelize.authenticate();
  console.log('Connection has been estabilished successfully.');
}catch{
  console.log('Unable to connect to the database.');
}
}

db_connection()

如何对 tc_devices table 进行简单查询?我应该在 database.js 中导入什么?在 tc_devices 中,我导出 function(sequelize, DataTypes)...但我不明白如何使用此功能在 database.js 中进行查询...您能帮帮我吗?非常感谢。

在使用这些模型执行第一个查询之前,您需要注册所有模型及其关联。看看.
只要你这样做,你就可以执行这样的查询:

// assuming db already stores all model definitions
const allRecords = await db.tcDevices.findAll({})