Today i will try to share about "How to connecting multiple database mongodb in nodejs server", so let see and try to anlyzing script below :
db.js
const mongoose = require('mongoose')
const MONGO_URI =
'mongodb+srv://owlhacking:mypassword@cluster0.ls5sgez.mongodb.net/qrCodeData?retryWrites=true&w=majority'
const MOBILE_URI =
'mongodb+srv://owlhacking:mypassword@cluster0.lpqs0es.mongodb.net/Cluster0?retryWrites=true&w=majority'
const connectDBs = () => {
try {
const qrCodeDb = mongoose.createConnection(MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
})
const userDB = mongoose.createConnection(MOBILE_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
})
return { qrCodeDb, userDB }
} catch (error) {
console.error(`Error:${error.message}`)
process.exit(1)
}
}
module.exports = { connectDBs }
model.js
const { default: mongoose } = require('mongoose')
const { connectDBs } = require('../config/db')
const qrSchema = mongoose.Schema({
qrInformation: {
type: String,
required: true
},
qrImage: {
type: String,
required: true
},
timeStamp: {
type: String,
default: Date()
}
})
const userSchema = new mongoose.Schema({
fullname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
})
const { qrCodeDb, userDB } = connectDBs()
module.exports = {
userSchema: userDB.model('user', userSchema),
Qrcode: qrCodeDb.model('Qrcode', qrSchema)
}
Hope this information can helping you. Thanks
Source : https://gist.github.com/hackinf0/4f97a6a7e820cb612e0ff5c39139d08f
No comments:
Post a Comment