Good morning, I have a Rest API that connects me with MongoDB without problems, but I want it to connect to MySQL, but I have not been able to remove MongoDB to put MySQL, I have made several attempts, but it does not connect to MySQL.
Original with MongoDB:
config.js
const mongoose = require('mongoose');
const dbConnection = async() => {
try {
await mongoose.connect( process.env.MONGODB_CNN, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log('Base de datos online');
} catch (error) {
console.log(error);
throw new Error('Error a la hora de iniciar la base de datos');
}
}
module.exports = {
dbConnection
}
.env
PORT=8080
MONGODB_CNN=mongodb+srv://cafe_user:[email protected]/CafeDB
SECRETORPRIVATEKEY=EsTaEsmiPalabr@secretaDeTokENS123321
CLOUDINARY_URL=cloudinary://776571654463621:2U14cGjxKWwFrA4GA6wQYNjW_H4@dwragjgy0
Now MySQL: (The part that doesn't work for me)
config.js
const mysql = require("mysql");
require("dotenv").config();
const dbConnection = async() => {
try {
await mysql.connect( process.env, {
host: 'process.env.DBHOST',
user: 'process.env.DBUSER',
password: 'process.env.DBPASSWORD',
database: 'process.env.DATABASE'
});
console.log('Base de datos online');
} catch (error) {
console.log(error);
throw new Error('Error a la hora de iniciar la base de datos');
}
}
module.exports = {
dbConnection
}
.env
PORT=8080
DBHOST: localhost
DBUSER: node_user2
DBPASSWORD: 123456
DATABASE: node_db
Update
I also add the server.js
, where I show the other configurations that exist, since when modifying config.js
for MySQL it also throws errors in the console of this file. I have tried various options but none works for me, it only works with MongoDB.
server.js
const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const { dbConnection } = require('../database/config');
class Server {
constructor() {
this.app = express();
this.port = process.env.PORT;
this.paths = {
auth: '/api/auth',
buscar: '/api/buscar',
categorias: '/api/categorias',
productos: '/api/productos',
usuarios: '/api/usuarios',
uploads: '/api/uploads',
}
// Conectar a base de datos
this.conectarDB();
// Middlewares
this.middlewares();
// Rutas de mi aplicación
this.routes();
}
async conectarDB() {
await dbConnection();
}
middlewares() {
// CORS
this.app.use( cors() );
// Lectura y parseo del body
this.app.use( express.json() );
// Directorio Público
this.app.use( express.static('public') );
// Fileupload - Carga de archivos
this.app.use( fileUpload({
useTempFiles : true,
tempFileDir : '/tmp/',
createParentPath: true
}));
}
routes() {
this.app.use( this.paths.auth, require('../routes/auth'));
this.app.use( this.paths.buscar, require('../routes/buscar'));
this.app.use( this.paths.categorias, require('../routes/categorias'));
this.app.use( this.paths.productos, require('../routes/productos'));
this.app.use( this.paths.usuarios, require('../routes/usuarios'));
this.app.use( this.paths.uploads, require('../routes/uploads'));
}
listen() {
this.app.listen( this.port, () => {
console.log('Servidor corriendo en puerto', this.port );
});
}
}
module.exports = Server;
One of your problems is that in
.env
MySQL you have:
instead of=
Pass it to the following:
Another problem is that you have only taken code that works with a MongoDB module and you have changed the parts that MongoDB puts into MySQL and you think that will work... They are completely different modules and have nothing to do with each other , you can't expect changing 4 names to work like nothing...
Change the
config.js
to the following:You will have to collect the return where you call the 'server.js' function , this happens because you need the
connecion
one you are declaring to perform the queries.I leave you the documentation of the MySQL node package so you can take a look at it