简体   繁体   中英

How to use Mysql and MongoDB on same NodeJs server?

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 ?

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.

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}`)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM