Home > Enterprise >  Sequelize, Express JS - Cannot read properties of undefined (reading 'findAll')
Sequelize, Express JS - Cannot read properties of undefined (reading 'findAll')

Time:06-22

I am working with Express JS and Sequelize which is connected to a MSSQL database. I am unable to perform any requests as I am getting the error "Cannot read properties of undefined (reading 'findAll')". Can anyone help out with this one?

Below is my set up:

Invites 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:

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:

'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;

CodePudding user response:

The require statement '../models/Invites' does not return an object with an invitesModel property.

You probably want to change your import statement to:

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

And then use

Invites.findAll(...);

to query the Invites model.

If you're not sure what a require statement is grabbing, you can add a log statement to check:

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

CodePudding user response:

try add '?'

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

};

  • Related