I'm having this issue on how can I connect my socket.io to my existing mongodb connection? Currently now I'm creating a task management app. I'm planning to add a chat features to my app. But I'm having this issue on how can connect this to my existing mongodb connection.
server.js
import express from 'express';
import cors from 'cors';
import http from 'http';
import { Server } from 'socket.io';
import path from 'path';
import connect from './dbconnect.js';
import accountRoutes from './routes/accountRoutes.js';
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/api/user', accountRoutes);
const __dirname = path.resolve('..');
app.use('/public/uploads', express.static(__dirname '/public/uploads/'));
const chatServer = http.createServer(app);
const PORT = process.env.PORT || 5000;
const socket = new Server(chatServer);
socket.on('connection', (socket) => {
console.log('a user connected');
});
**Connection from my existing mongodb database**
connect
.then(() => {
app.listen(PORT, () =>
console.log(`Server Running on Port: http://localhost:${PORT}`)
);
})
.catch((error) => console.log(`${error} did not connect`));
dbconnect.js
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const connect = mongoose.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
export default connect;
CodePudding user response:
This is how I setup my database connection,
db.connect.js
import mongoose = require('mongoose');
const options ={
user:`${config.mngusername}`,
pass:`${config.mngpassword}`,
keepAlive: true,
keepAliveInitialDelay: 300000,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
const MONGO_URI = `mongodb://${config.mongourl}:${config.mongoport}/${config.mongocollection}?authSource=admin`;
try {
mongoose.set('useFindAndModify', false);
mongoose.connect(MONGO_URI, options);
mongoose.connection.on('connected', ()=>{
console.log({status:true,msg:'Mongoose default connection open to ' MONGO_URI},'service');
});
// If the connection throws an error
mongoose.connection.on('error', (err)=>{
console.log({status:false,msg:'handle mongo errored connections: ' err},'service');
});
// When the connection is disconnected
mongoose.connection.on('disconnected', ()=>{
console.log({status:false,msg:'Mongoose default connection disconnected'},'service');
});
process.on('SIGINT', ()=>{
mongoose.connection.close(()=>{
console.log({status:false,msg:'App terminated, closing mongo connections'},'service');
process.exit(0);
});
});
} catch (error) {
console.log({status:false,msg:error},'service');
}
Then you would only import your DB script in your main script using :
require('locationofdbscript');
And start your socket io server normally without having the dependence on the DB connection. The DB script will log if the connection was successful or not and it will also automatically retry failed connections.
Hope that works for you.