Sequelize Error: Undefined property 'define' being accessed

I am attempting to add a new record to a MYSQL table using sequelize.

After installing sequelize and mysql, I ran the following commands:

npm install --save sequelize

npm install --save mysql

In my app.js file, I included the following:

var Sequelize = require('sequelize');

In my db.js file, I set up the database connection as follows:

var Sequelize = require('sequelize');

var sequelize = new Sequelize('randomdb', 'root', 'root', {
    host: 'localhost',
    dialect: 'mysql',
    port : 8889,

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

exports.sequelize = sequelize;
module.exports = Sequelize;

Within routes/index.js, I defined the routes for adding a user:

var express = require('express');
var router = express.Router();
var sequelize = require('../db').sequelize;

router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

router.get('/adduser', function (req, res) {
    var User = sequelize.define('users', {
        first_name: Sequelize.STRING
    });

    sequelize.sync().then(function () {
        return User.create({
            first_name: 'janedoe'
        });
    }).then(function (jane) {
        console.log(jane.get({ plain: true }));
    });
});

module.exports = router;

An error was encountered with the message:

Cannot read property 'define' of undefined

TypeError: Cannot read property 'define' of undefined

To address this issue, I made the following changes:

EDIT 2

Updated db.js:

var Sequelize = require('sequelize');

var sequelize = new Sequelize('randomdb', 'root', 'root', {
    host: 'localhost',
    dialect: 'mysql',
    port: 8889,

    pool: {
        max: 5,
        min: 0,
        idle: 10000
    },
    define: {
        timestamps: false
    }
});

var db = {};

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

module.exports = db;

Created models/user.js:

var db = require('../db'),
    sequelize = db.sequelize,
    Sequelize = db.Sequelize;

var User = sequelize.define('random', {
    first_name: Sequelize.STRING
});

module.exports = User;

Modified routes/index.js:

var express = require('express');
var router = express.Router();
var db = require('../db'),
    sequelize = db.sequelize,
    Sequelize = db.Sequelize;

var User = require('../models/user');

router.get('/adduseryes', function (req, res) {
    sequelize.sync().then(function () {
        return User.create({
            first_name: 'janedoe'
        });
    }).then(function (jane) {
        res.send("YES");
    });
});

module.exports = router;

Answer №1

Your db.js file is currently replacing the exports variable with the Sequelize variable. In Node.js, module.exports essentially equals exports. To fix this issue, consider implementing the following changes:

var Sequelize = require('sequelize');

var sequelize = new Sequelize(...);

var db = {};

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

module.exports = db;

After making these adjustments in db.js, update your import statement in routes/index.js as shown below:

var db = require('../db'),
  sequelize = db.sequelize,
  Sequelize = db.Sequelize;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to transfer the array from express to mongoDB

I am attempting to send an array to MongoDB through an express post request. app.post('/createGroup', (req, res) => { const { title, description, tenants } = req.body; const group = { title: title, description: descript ...

Middleware for cascading in Mongoose, spanning across various levels in the

I have been working on implementing cascading 'remove' middleware with mongoose for a project. In my database structure, I have nested collections as follows: 'modules' -> 'modulesInst' -> 'assignments' -> ...

The URL "http://localhost:8100" has been restricted by the CORS policy, as it lacks the necessary 'Access-Control-Allow-Origin' header on the requested resource

`The CORS policy has blocked access to the XMLHttpRequest at 'http://localhost/phpfile/leave-option.php' from the origin 'http://localhost:8100'. This is due to the absence of the 'Access-Control-Allow-Origin' header on the re ...

Ways to create an object based on another object

Currently, I am teaching myself Javascript. My focus is on working with Vuejs and express for a CRUD App. In one of my components, I retrieve data from my backend using the API: localhost:3000/api/transport. The response contains all objects from the data ...

Node.js and TestCafe encountered a critical error: Inefficient mark-compacts were performed near the heap limit, resulting in an allocation failure. The JavaScript heap ran

While executing my test scripts in Node v14.6.0, I encountered the following problem. Here are some of the options I've tried: I attempted to increase the Node Heap Size but unfortunately had no success: export NODE_OPTIONS=--max_old_space_size=4096 ...

Guide to changing the status code to 404 for a 404-page in Next.js

I have been trying to figure out how to set a 404 status code for the 404-page in Next.js. The response I received stated that the status code is already 404 by default, but upon closer inspection, it seems that all bad requests are returning a 404 status ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

What is the process for enabling external host access to a port in a Docker container?

I've been working on exposing a port in my Docker container and attempting to connect an application from an external host, but I'm having trouble establishing a connection. Here is the curl request: curl http://localhost:4400 curl: (56) Recv fa ...

Difficulty encountered while executing Protractor tests with Selenium Server

Attempting to Execute Protractor/Jasmine/Selenium End-to-End Tests Currently in the process of running end-to-end tests using Protractor with the standalone Selenium server and the chrome driver. Encountering a Selenium server error when attempting to ru ...

Troubleshooting static resource serving in Node.js on OpenShift

After setting up a basic node0.10 cartridge on OpenShift, I encountered an issue with my index.html file where I couldn't access certain files from the node_modules folder. Instead, I kept receiving 404 http errors. The imports in my index.html are s ...

Setting a cap on file sizes in Azure websites

I am currently attempting to upload a file from the front-end to the back-end and save the file on Azure Storage. My code functions properly when the file size is below 30mb, however, it fails if the file size exceeds 30mb. console.log('- 11111 -&apo ...

Tips for locating multiple precise values within a specific field in an Elasticsearch query

Below is a glimpse of my data: {"listings":{"title" : "testing 1", "address" : { "line1" : "3rd cross", "line2" : "6th main", "line3" : "", "landmark" : "", "location" : "k r puram", "pincode" : "", "city" : "Bangalore" },"purpose":"rent","published": tru ...

Can you explain the meaning of this error message: Invalid value provided for recipient key 'registrationTokens'?

I encountered an issue involving a Falsy value for the recipient key 'registrationTokens' whilst working on GCM push notifications. Here is the code snippet in question: Device.find({ user: { $in: users }}, function (err, devices) { i ...

Attempting to start a node application on a Fedora server

Hi there, I'm currently working on building a website and planning to use MongoDB, Express, etc. I have set up a server using the Fedora Server ISO, but I'm facing issues with getting Node.js to work properly. Despite following multiple tutorials ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

Using Express.js to send a response while simultaneously executing a background task

When working with Express.js, I have a need to execute a task after sending a response. My main goal is to minimize the response time and send back the response immediately without waiting for the task results to be returned to the client. The task itself ...