如何使用 mongoose 将我的 socket.io 连接到我现有的 mongodb 连接

How to connect my socket.io to my existing mongodb connection using mongoose

我遇到了关于如何将 socket.io 连接到现有 mongodb 连接的问题?目前我正在创建一个任务管理应用程序。我打算在我的应用程序中添加聊天功能。但是我遇到了关于如何将其连接到我现有的 mongodb 连接的问题。

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;

这就是我设置数据库连接的方式,

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');
}

那么您只需使用以下命令在您的主脚本中导入您的数据库脚本:

require('locationofdbscript');

并在不依赖数据库连接的情况下正常启动您的套接字 io 服务器。 数据库脚本将记录连接是否成功,并且还会自动重试失败的连接。

希望对你有用。