4

I have a REST API in NodeJS and Express JS. Here's the basic thing what I need to implement. There's a database in mysql and my node js server read the database in some specific conditions and need to make a log in MongoDB server. It is the architecture and it can't be changed. So is it possible to use both MySQL and MongoDB in same NodeJs server ?

2 Answers 2

4

Yes it's 100% possible, they use completely different ports and do not care about each other.

The server isn't a 'nodejs' server, it's a server that's running nodejs, and you can install anything you want on the server.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah thanks a lot. And also I searched a lot and still no answer. Do you have some code snippet or link which showing the way.
There's no code snippet just install them on the server
1

either you can directly write following mongodb and mysql database connection code in youe app.js (starter file) file

or you can write is separate files for mongo and mysql connection as follows:

step 1. create file named as mongodb_con.js

mongoose.connect('mongodb://localhost:27017')
.then(sucess => {
    console.log("connected with mongo server...")
})
.catch(error => {
    console.log("error while connecting to database...")
})

step 2. create file named as mysql_con.js

const mysql = require("mysql")

var con = mysql.createConnection({
host: "localhost", //your hostname
user: "root",      //your username
password: "root",  //your password 
database: "detabase_name" //your database name
})

con.connect((error) => {
if (!error) {
    console.log("connected with sql server")
}
else {
    console.log("Error in Making Connection...", error)
}
})

step 3. in final stepjust import both file in app.js

const express = require('express')
const app = express()
require('./mongodb_con.js')
require('./mysql_con.js')
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.