NodeJS sequelize.query()不是函数

63lcw9qa  于 2022-12-22  发布在  Node.js
关注(0)|答案(3)|浏览(198)

我是新来的续集。我试图使用行查询,但我得到了一个错误。
代码:

const sequelize = require('sequelize');

sequelize.query("SELECT * from users").then(results => {
      console.log(results);
   })

调用此API时出错:

(node:2380) UnhandledPromiseRejectionWarning: TypeError: sequelize.query is not a function
    at Promise (C:\NodejsProject\mars\app\schedule\models\schedule.js:247:17)
    at new Promise (<anonymous>)

我该怎么补救呢?

jfewjypa

jfewjypa1#

您不能直接从require('sequelize');使用sequelize,首先我们需要创建该示例,而示例将从数据库详细信息创建,因此sequelize可以知道它在哪个平台上运行查询,使用哪个数据库
下面是基本的代码片段,只是为了说明一下:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'|'sqlite'|'postgres'|'mssql',

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite',

  // http://docs.sequelizejs.com/manual/tutorial/querying.html#operators
  operatorsAliases: false
});

sequelize.query("SELECT * from users").then(results => {
    console.log(results);
});

有关详细信息:* * 一个

wgmfuz8q

wgmfuz8q2#

如果您正在外部文件中运行数据库配置,并且希望有额外的层来防止SQL注入。/database/dbs. js

const Sequelize = require('sequelize')
const db = {}
const sequelize = new Sequelize('dbname', 
                                'username', 
                                'password', {
  host: 'localhost',
  dialect: 'mysql',
  logging: console.log,
  freezeTableName: true,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db

然后在要使用的文件中:

const db        = require('../database/db')
...
    const newDbName = 'myNewDb'
    db.sequelize.query(`CREATE DATABASE IF NOT EXISTS ${newDbName} `, {
        type: db.sequelize.QueryTypes.CREATE
    }).then( () => {
        res.send('ok done creating ' + req.body.newDbName).end()
    }).catch( err => {
        res.status(500).send('Err executing command ' + err).end()
    })
dgjrabp2

dgjrabp23#

//数据库连接. js
const sequelize =需要("sequelize");
const con =新序列化。序列化(

'db',
"user",
"password",

{
    host: "localhost",
    dialect: "mysql",
    operatorsAliases: false,
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    },

},

);
条件查询("选择1",(错误,行)=〉{
控制台日志(行)
如果(err)抛出err;
控制台日志(错误)
}). then(函数(结果){
控制台日志("清单")
控制台日志(结果)
});
模块输出= con;
//结束数据库连接. js
//输入
设con =必需("../公用/数据库连接")
//在函数中使用
const [结果,元数据]=等待条件查询("SELECT * FROM官员JOIN用户ON官员.用户ID =用户.用户ID");
控制台日志(JSON字符串化(结果,空,2));

相关问题