I am new to nodejs and Sequelize and have been having an issue that I cannot figure out how to get over. I want to use a connection I created and exported it to a module.
Like this:
const dotEnv = require('dotenv');
const Sequelize = require('sequelize');
dotEnv.config();
module.exports.connection = async () => {
try{
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql',
logging: false,
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
});
await sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(error => {
throw error;
});
}catch(error){
throw error;
}
}
I then have another file where I want to use it that looks like this
const Sequelize = require('sequelize');
const { connection }= require('../database');
const accountModel = connection.define('accounts', {
// attributes
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true
},
password: {
type: Sequelize.STRING,
allowNull: false,
//is: /^[0-9a-f]{64}$/i
},
permission: {
type: Sequelize.STRING,
allowNull: false
},
discount: {
type: Sequelize.INTEGER,
allowNull: false
}
}, {
freezeTableName: true
});
module.exports = connection.model('accounts', accountModel);
The problem is that I get told that: TypeError: connection.define is not a function,
The connection works, the database is running, everything else works
And last if I do it like this, it works too:
const dotEnv = require('dotenv');
const Sequelize = require('sequelize');
dotEnv.config();
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql',
logging: false,
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
});
const accountModel = sequelize.define('accounts', {
// attributes
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true
},
password: {
type: Sequelize.STRING,
allowNull: false,
//is: /^[0-9a-f]{64}$/i
},
permission: {
type: Sequelize.STRING,
allowNull: false
},
discount: {
type: Sequelize.INTEGER,
allowNull: false
}
}, {
freezeTableName: true
});
module.exports = sequelize.model('accounts', accountModel);
I am really not sure why the module one does not work but the direct method does. I have tried to search Google and Stack Overflow for a solution.
The problem in your first approach is that you exported first of all an async function and not the Sequelize instance (as it is in your second example) and secondly the function itself is not returning anything. That's why there is no connection.define() function when you require that in another file.
try this in database.js and it should work:
module.exports.connection = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql',
logging: false,
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
});
You can do all that authenticate() and try {} catch (error) {} somewhere else for example in your very first js file where you starting the server by requiring the same database.js file. But for the model definitions it's important that you are exporting just the new Sequelize() instance to them to be able to use define()
I would do something like this. In the connections file you export the function then in the accountModel file you import and invoke the function.
connection.js:
exports.connection= async function() { // Stuff here }
accountModel.js:
const { connection }= require('../database');
let connection = await connection.connection();
Related
I was trying to connect and get data from oracle database using sequelize, but it was returning an error Cannot read properties of undefined (reading 'length'): undefined
Here is the code :
Connection
import { Sequelize, DataTypes } from "sequelize";
import _projects from "../models/projects.js";
export const getProjects = async (req, res, next) => {
var conn = new Sequelize({
dialect: 'oracle',
username: dbAdmin,
password: dbPass,
dialectOptions: { connectString: connStr } // also tried { connectionString: connStr }
});
function initModel(connection) {
const projects = _projects.init(connection, DataTypes);
return { projects };
}
var db = initModel(conn);
const all_projects = await db.projects.findAll()
console.log("all_projects", all_projects.rows); // Cannot read properties of undefined (reading 'length'): undefined
}
projects.js
import _sequelize from 'sequelize';
const { Model, Sequelize } = _sequelize;
export default class projects extends Model {
static init(sequelize, DataTypes) {
return super.init({
id: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true
},
credat: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: Sequelize.fn('getdate')
},
description: {
type: DataTypes.STRING(1024),
allowNull: true
},
picture: {
type: DataTypes.STRING(255),
allowNull: true
},
settings: {
type: DataTypes.TEXT,
allowNull: true
},
is_deleted: {
type: DataTypes.INTEGER,
allowNull: true
}
}, {
sequelize,
tableName: 'projects',
schema: 'dbo',
timestamps: false,
});
}
}
It seems like you confused findAll with findAndCountAll which returns rowa and count and also you didn't indicate any parameters at all (which can lead to this error with undefined) in findAll:
Compare:
const all_projects = await db.projects.findAll({})
console.log("all_projects", all_projects);
and
const a_page_of_projects = await db.projects.findAndCountAll({
limit: 10,
offset: 0
})
console.log("a_page_of_projects rows", a_page_of_projects.rows);
console.log("a_page_of_projects count", a_page_of_projects.count);
const Sequelize = require("sequelize");
const db = require("../db");
const user = require("../models/userModel");
const employees = db.define("employees", {
firstname: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
lastname: {
type: Sequelize.STRING,
allowNull: false,
},
userId: {
type: Sequelize.INTEGER,
references: {
model: user,
key: "id",
},
},
});
employees.sync({ alter: true });
module.exports = employees;
Okay,so I have two tables already created, in my terminal they appear with create table if not exists but not for this table,but not for this table,I missed something? pg version :8.7.1
const { Sequelize } = require("sequelize");
const sequelize = new Sequelize("xxx", "xxx", "xxx", {
host: "localhost",
dialect: postgres,
port: 5000,
});
module.exports = sequelize;
db file
sync is (ironically) an asynchronous operation. You need to await it:
await employees.sync({ alter: true });
I've been trying to create associations with Sequelize but to no avail, I kept getting a hasOne is not a function error. I've learned that it may be because of circular dependencies with my imports. So I started using the Sequelize instance in my index.js file and importing that instance in other model files:
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 = {};
const practAppt = require('./practAppt')
const practUser = require('./practUsers')
practAppt.hasOne(practUser, {foreignKey: "email"})
practUser.hasMany(practAppt, {foreignKey: "client"})
var sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'C:/backend/db.sqlite3'
});
//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 => {
console.log("FILE", file)
const model = require((path.join(__dirname, file)));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
practUsers.js
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const db = require("./index")
const practUser = db.define("practUsers", {
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
address: {
type: Sequelize.STRING,
allowNull: false
},
unit: {
type: Sequelize.STRING,
allowNull: false
},
city: {
type: Sequelize.STRING,
allowNull: false
},
province: {
type: Sequelize.STRING,
allowNull: false
},
postal_code: {
type: Sequelize.STRING,
allowNull: false
},
phoneNumber: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
birthdate: {
type: Sequelize.STRING,
allowNull: false
},
healthCardNumber: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
profession: {
type: Sequelize.STRING,
allowNull: false
},
designation: {
type: Sequelize.STRING,
allowNull: false
},
userType: {
type: Sequelize.STRING,
allowNull: false
},
})
// automatically create the table with the model definition
//sequelize.sync()
// test the connections
module.exports = {practUser}
But now it's telling me db.define is not a function, even if I export sequelize in index.js I get the same error. How do I properly create associations? I should create them in index.js correct? Or does it not matter? The docs seems to be useless on this front.
your db object as exported from index.js doesn't have the define method. You probably need to write:
const practUser = db.sequelize.define(....
I have 2 express.js applications and run sequelize.sync(), but in my first app it generate the tables, and the others not generate the tables, i wonder why, because the script is identic.
database.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('student-affairs', 'root', '', {
dialect: 'mysql',
host: 'localhost',
operatorsAliases: false,
});
module.exports = sequelize;
organization.js
const Sequelize = require('sequelize');
const sequelize = require('../configs/database');
const Organization = sequelize.define('organization', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
logo: {
type: Sequelize.STRING
},
createdBy: {
type: Sequelize.INTEGER,
allowNull: false
},
updatedBy: {
type: Sequelize.INTEGER,
allowNull: false
}
});
module.exports = Organization;
app.js
// Database
const sequelize = require('./configs/database');
sequelize
.sync()
.then(result => {
console.log(result);
app.listen(3001);
})
.catch(err => {
console.log(err);
});
But after i log it, it always return the models empty like this
models: {},
modelManager: ModelManager { models: [], sequelize: [Circular] },
it doesn't have the models. anyone can explain why? thanks
I just realize that i am not call the organization model in app.js, once i define it in app.js and it fix the problem.
I think it's a basic mistake. Now i understand how it works.
// Models
const Organization = require('./models/organization');
sequelize
.sync()
.then(result => {
app.listen(3000);
})
.catch(err => {
console.log(err);
});
I try to use Sequelize ORM. Reading documention to this i saw the example
const Project = sequelize.define('project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
const Task = sequelize.define('task', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
deadline: Sequelize.DATE
})
I solved to apply practically in shell node.
I started node in command line
var sequelize = require('sequelize')
sequelize.define ...
But node said me it is wrong and sequelize dont have the method "define".
SO i think now where is my error and im wrong understand documentation
You need to create an instance of sequelize:
const Sequelize = require("sequelize");
const sequelize = new Sequelize(
database,
username,
password,
{
host: host,
logging: false,
dialect: "mysql",
port: 3306,
pool: {
max: 5,
min: 0,
idle: 10000
}
}
);
And after that do define:
const Project = sequelize.define('project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
const Task = sequelize.define('task', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
deadline: Sequelize.DATE
})