I am new to sequelize and I created a middleware called "db.js" with a connection to a mysql table called "users". Everytime, I attempt to run the app.js, I am getting this error: "TypeError: app.use() requires a middleware function".
However, I have a middleware function. See the code below: Am I missing something? I have the module.exports object at the end.
Should I have initialize sequelize?
db.js file
const Sequelize = require("sequelize");
const mysql = require("mysql");
const mysql2 = require("mysql2");
const db = {}
const sequelize = new Sequelize("smalldata", "root", "xxxx", {
host: "localhost",
dialect: "mysql",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 90000
}
})
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;
app.js file
const sequelize = require("sequelize");
const db = require("./middleware/db");
const express = require("express");
//Initialize Middleware
app.use(cors());
app.use(expressLayouts);
app.use(logger);
app.use(db);
user.js file
const Sequelize = require("sequelize");
const db = require("./db");
const User = db.sequelize.define(
'users',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
}
},
{
timestamps: true
},
)
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model
definition
return User.create({
first_name: 'John',
last_name: 'Hancock',
email:'johnhancock#gmail.com',
password:'johnny'
});
});
module.exports = User
I found the error:
Capitalize error in app.js file:
const Sequelize = require("sequelize");
instead of:
const sequelize = require("sequelize");
Related
i have a problem with adding a collection into my database in mongodb atlas.
I have managed to import this collection before but i accidentally deleted it and now i can't upload it again. there is no error in my terminal. There for i don't know what is wrong with my code.. (image of my code and terminal are attached below)
There is anyone who might know why is this can happen?
EDIT
I tried to open a new database and my all the collections was imported to it and once again, only the product collection doesn't
//////////////////////////////////
/* require('dotenv').config({ path: '/.env' }) */
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '..', '.env') })
console.dir(process.env.MONGO_URI)
const mongoose = require('mongoose')
const connectDB = async () => {
try {
mongoose.connect(process.env.MONGO_URI, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('MongoDB connection SUCCESS')
} catch (error) {
console.error('MongoDB connection FAIL')
process.exit(1)
}
}
console.dir(process.env.MONGO_URI)
module.exports = connectDB
////////////////////////////////////////////////////////////////
require('dotenv').config()
const productsData = require('./data/products')
const connectDB = require('./config/db')
const Product = require('./models/product')
connectDB()
const importData = async () => {
try {
/* Product.deleteMany({}) */
Product.insertMany(productsData)
console.dir('Data Imported Successfuly')
process.exit()
} catch (error) {
console.log(error)
console.error('Error Ocured In Imported Data Process', error)
process.exit(1)
}
}
importData()
my model schema
const mongoose = require('mongoose')
const products = require('../data/products')
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
module.exports = mongoose.model('Products', productSchema)
my code and terminal image
Product.insertMany(productsData) returns a promise, but you aren't waiting for that promise to finish before exiting the process. Add an await before it and you should be okay.
Try this to create your schema instead
const { Schema } = mongoose;
const productSchema = new Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
const Product = mongoose.model("Product", productSchema);
Product.createCollection();
TypeError: Cannot read property 'findAll' of undefined
findAll function makes error, but Connection was successful.
And database is also created under the name managers.
app.js
models
index.js
maria
manager.model.js
bin
www.js
models/index.js
const { Sequelize } = require('sequelize');
const manager = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxx',
password: 'xxx',
database: 'test',
timezone: 'Asia/Seoul'
});
require('./maria/manager.model')(manager);
module.exports=manager;
models/maria/manager.model.js
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
sequelize.define('manager', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING,
}
}, {timestamps: true }).sync({force:false});
};
app.js
const express = require('express');
const app = express();
const db = require('./models');
console.log(`Checking database connection...`);
// It works!
db.authenticate().then(()=>{
console.log('Database connection OK!');
});
// It makes error!
const find_test = db.manager.findAll();
console.log(find_test);
First of all what is containing your manager variable ?
your manager variable is containing the connection sequelize. Your objectif is to request your table manager but you can't to this with the variable. Because he doesn't contain table specification but database connection.
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
return sequelize.define('manager', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING,
}
}, {timestamps: true });
};
In this file, you need to return the definition of your table.
const { Sequelize } = require('sequelize');
const manager = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxx',
password: 'xxx',
database: 'test',
timezone: 'Asia/Seoul'
});
const myTable = require('./maria/manager.model')(manager);
module.exports= {
manager, myTable
};
and in this file, you need to store the return value in a variable.and export it.
const express = require('express');
const app = express();
const { manager, myTable }= require('./models');
console.log(`Checking database connection...`);
// It works!
manager.authenticate().then(()=>{
console.log('Database connection OK!');
});
const find_test = myTable.findAll();
console.log(find_test);
Finaly in the next file, import the new exported variables ! and Enjoy !
app.js
sequelize
models
manager.model.js
index.js
app.js
const maria = require('./sequelize');
const { models } = require('./sequelize');
console.log(`Checking database connection...`);
maria.authenticate()
.then(()=>{
console.log('Database connection OK!');
});
const test = models.manager.findOne()
sequelize/index.js
const { Sequelize } = require('sequelize');
const maria = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxxx',
password: 'xxxx',
database: 'test',
timezone: 'Asia/Seoul'
});
require('./models/manager.model')(maria)
module.exports=maria;
I am learning to use sequelize with my Next.js app.I set up the sequelize, used the cli to generate migrations, created the model (user) , and when i try to test it, going to the http://localhost:3000/api/app . i get an error -> Cannot read property 'findAll' of undefined.
my model class is coming up as undefined. anyone has any idea?
*director structure
MyApp
...
> database
- db.js
> migrations
> models
-user.js
> node_modules
> pages
> api
- app.js
db.js
const Sequelize = require('sequelize');
const db = new Sequelize('mydb', 'root', 'pass', {
host: "localhost",
port: 3306,
dialect: 'mysql',
operatorsAliases:false,
logging: function () {},
pool: {
max: 5,
min: 0,
idle: 10000
},
dialectOptions: {
socketPath: "/var/run/mysqld/mysqld.sock"
},
define: {
paranoid: true
}
});
db.authenticate().then(() => {
console.log('connection error');
}).catch(err => {
console.log('Connection successful');
});
module.exports = db;
model/User.js
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define("User", {
id : {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement:true,
primaryKey:true
},
firstName : {
type: DataTypes.STRING(50),
allowNull: false
}
lastName : {
type: DataTypes.STRING(50),
allowNull: false
},
created: {
type: 'TIMESTAMP',
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
allowNull: false
},
updated:{
type: 'TIMESTAMP',
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
allowNull: false
}
});
return user;
};
pages/api/app.js
const models = require('../../models')
export default (req, res) => {
models.user.findAll(); //error => Cannot read property 'findAll' of undefined
};
You define uppercase User in the User.js file, so you have to use it uppercase:
const models = require('../../models');
export default async (req, res) => {
const users = await models.User.findAll();
console.log(users);
};
I recently developed a react app with nodejs which depends on mongodb for its data. I have also just installed mongodb on Google Compute Engine and opened port 27017. However, my question is, how can i connect my application (I am using Mongoose) to the VM Instance.
Here is the connection string on localhost (my local machine), what should I change it to:
module.exports = {
url: 'mongodb://localhost:27017/dapashirts'
}
Here is my server.js file:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Connecting to the database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
// Require routes
require('./routes/department.routes.js')(app);
require('./routes/category.routes.js')(app);
require('./routes/product.routes.js')(app);
require('./routes/order.routes.js')(app);
app.listen(3500, () => {
console.log("Server is listening on port 3500");
});
Here is a sample model:
const mongoose = require('mongoose');
const ProductSchema = mongoose.Schema({
category_id: {
type: [mongoose.Schema.Types.ObjectId],
required: true
},
name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
discounted_price: {type: Number, default: 0.00},
image: String,
image_2: String,
thumbnail: String,
display: { type: Number, min: 0, max: 3, default: 0 }
});
module.exports = mongoose.model('Product', ProductSchema);
Here is a sample route:
module.exports = (app) => {
const products = require('../controllers/product.controllers.js');
// Create a new product
app.post('/products', products.create);
// Retrieve all products
app.get('/products', products.findAll);
// Retrieve a single product with productId
app.get('/products/:productId', products.findOne);
// Retrieve a products with categoryId
app.get('/products/:categoryId', products.findWithCategoryId);
// Update a product with productId
app.put('/products/:productId', products.update);
// Delete a produt with productId
app.delete('/products/:productId', products.delete);
}
How do i also transfer my localhost database to Google Compute Engine
The easiest way is to use a database as a service (daas) from Mongo DB:
https://www.mongodb.com/cloud/atlas
I'm new in node.
I'm trying to add Sequelize in my simple application with cosign.
config/db.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('test', 'root', '', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
module.exports = function () {
return sequelize
}
model/user.js
var Sequelize = require('sequelize');
module.exports = function(application, req, res){
var User = sequelize.define('user', {
username: {
type: Sequelize.STRING,
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
User.create({ username: 'fnord'})
.then(function() {
console.log('criado!');
})
}
config/server.js
...
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(app);
module.exports = app;
I'm getting the error sequelize is not definedĀ“ onvar User = sequelize.define('user', {`
What I'm doing wrong?
Create an index.js file inside your moldes folder like this:
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var sequelize = new Sequelize(global.config.dbConfig.name, global.config.dbConfig.user, global.config.dbConfig.password, {
host: global.config.dbConfig.host,
port: global.config.dbConfig.port,
pool: false
});
var db = {};
fs.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
and in your user.js do something like this:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});
return User;
}
http://docs.sequelizejs.com/en/1.7.0/articles/express/
You should require sequelize instance into user model
config/db.js
module.exports = sequelize;
model/user.js
var Sequelize = require('sequelize');
var sequelize = require('../config/db.js'); //sequelize instance
module.exports = function(application, req, res){
var User = sequelize.define('user', {
...
The Sequelize-CLI is a very useful tool for projects that use Sequelize. When you download it
npm install -g sequelize-cli
You can then run
sequelize init
The above command will go and write out a few folders for you including a models folder that has the index file that Ricardo created above. This gives some really cool environment configuration as well. Within the new models folder, you can create a new file with your object with the syntax...
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});
return User;
}
While I do like this as a tool. It is key here to notice that Sequelize will go and look for the first argument to the define() method. So we could just write
module.exports = function(sequelize, DataType){
return sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});