简体   繁体   English

Sequelize,Express JS - 无法读取未定义的属性(读取“findAll”)

[英]Sequelize, Express JS - Cannot read properties of undefined (reading 'findAll')

I am working with Express JS and Sequelize which is connected to a MSSQL database.我正在使用连接到 MSSQL 数据库的 Express JS 和 Sequelize。 I am unable to perform any requests as I am getting the error "Cannot read properties of undefined (reading 'findAll')".我无法执行任何请求,因为我收到错误“无法读取未定义的属性(读取‘findAll’)”。 Can anyone help out with this one?谁能帮忙解决这个问题?

Below is my set up:下面是我的设置:

Invites Model:邀请Model:

module.exports = (sequelize, DataTypes) => {
    const Invites = sequelize.define("Invites", {
        Id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        Recipient: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        Code: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        Score: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        Status: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        Created: {
            type: DataTypes.DATE,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        ExpiresOn: {
            type: DataTypes.DATE,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        }
    });

    return Invites;
};

inviteController:邀请控制器:

const { invitesModel } = require('../models/Invites');

const getAllInvites = (req, res) => {
    invitesModel.findAll().then((invites) => {
        res.send(invites);
    }).catch((err) => {
        console.log(err);
    })
};


module.exports = {
    getAllInvites,
}

index.js:索引.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const db = require('./models');
const invitesController = require('./controllers/inviteController');
const cookieParser = require('cookie-parser');
const PORT = process.env.PORT || 5000;

app.use(cors()); //Cross origin resource sharing
app.use(express.json()); 
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());


//Get invite data
app.route('/api/invites').get(invitesController.getAllInvites);


db.sequelize.sync().then((req) => {
  app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
  });  
});


/models/index.js: /模型/index.js:

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

The require statement '../models/Invites' does not return an object with an invitesModel property. require 语句'../models/Invites'不返回具有invitesModel属性的 object。

You probably want to change your import statement to:您可能希望将导入语句更改为:

const { Invites } = require('../models');

And then use然后使用

Invites.findAll(...);

to query the Invites model.查询邀请model。

If you're not sure what a require statement is grabbing, you can add a log statement to check:如果您不确定 require 语句获取的是什么,您可以添加一个日志语句来检查:

const modelsObj = require('../models');
console.log(Object.keys(modelObj); // or console.log(JSON.stringify(modelsObj);

try add '?'尝试添加“?”

const getAllInvites = (req, res) => {
invitesModel?.findAll()?.then((invites) => {
    res.send(invites);
}).catch((err) => {
    console.log(err);
})

}; };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法读取未定义的 sequelize express JS 的属性“findAll” - Cannot read property 'findAll' of undefined sequelize express JS 类型错误:无法读取未定义的属性(读取“findAll”) - TypeError: Cannot read properties of undefined (reading 'findAll') 为什么 sequelize 不识别 Model? 类型错误:无法读取未定义的属性(读取“findAll”) - Why does sequelize not recognize the Model? TypeError: Cannot read properties of undefined (reading 'findAll') Sequelize.js/Node.js/Express.js:Tasks.findAll() 返回一个 TypeError:Cannot read property 'findAll' of undefined - Sequelize.js/Node.js/Express.js: Tasks.findAll()returns a TypeError:Cannot read property 'findAll' of undefined 无法读取 undefined sequelize express JS 的属性“findAll”并且 req.body 是一个空对象 - Cannot read property 'findAll' of undefined sequelize express JS and req.body is an empty object Sequelize TypeError:无法读取未定义的属性(读取“拆分”) - Sequelize TypeError: Cannot read properties of undefined (reading 'split') node.js/express.js 连接池无法读取未定义的属性(读取“getConnection”) - node.js/express.js connection pool Cannot read properties of undefined (reading 'getConnection') 类型错误:无法读取未定义的属性(读取“原型”)。 Next.Js 和 Express - TypeError: Cannot read properties of undefined (reading 'prototype'). Next.Js and Express Express.js 应用程序错误:无法读取未定义的属性(读取“传输编码” - Express.js application error: Cannot read properties of undefined (reading 'transfer-encoding' Express JS TypeError:无法读取未定义的属性(读取“0”)SQL 查询错误 - Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM