【发布时间】: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