【问题标题】:How to pass mongodb database connection through routes in Node?如何通过Node中的路由传递mongodb数据库连接?
【发布时间】:2021-11-07 00:03:13
【问题描述】:

我需要将 mongo 的连接从 index.js 传递到其他路由,我认为可以创建一个文件,其中包含定义与数据库的连接的说明,以便我可以在其他路由中调用它,但我不知道怎么做。这个论坛上的其他例子对我没有多大帮助。下面我附上代码。

//Database connection
mongoose.connect("mongodb://localhost:27017/codingWaifus", {useNewUrlParser: true}, function(err, db){
  if(err){
    console.log(err);
  }
  else{
    console.log("Connected to "+mongoose.connection.name+" on Port: "+mongoose.connection.port);
  }
});
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

【问题讨论】:

  • 您需要到数据库的原始连接吗? Mongoose 通常与为您进行查询的模型一起使用。如果您只需要使用模型,您可以将连接保留在 index.js 文件中,并在您的路由中需要模型并在那里使用它们。

标签: javascript node.js database mongodb express


【解决方案1】:

您可以通过以下方式执行此操作:

db.js

const mongoose = require('mongoose');
const dotenv = require('dotenv').config();

const connectDB = () => {
    mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true});

    mongoose.connection
    .once('open', () => { 
        console.log('Connection to the DB established');
    })
    .on('error', (err) => { 
        console.log('Error occured while connecting to the DB', err);
    })
}

module.exports = connectDB;

index.js

const connectDB = require('./db');
 
// Connecting to the DB
connectDB();

但是为什么一开始就已经建立了连接,还要再次调用MongoDB连接呢?

【讨论】:

  • 因为我需要在某些路由中执行一些查询
  • @GigiCarti 我的回答能解决你的问题吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 2015-03-20
  • 2017-04-23
  • 2016-11-12
  • 2010-09-19
  • 2021-09-08
相关资源
最近更新 更多