To do that you have to import the file which contains the MongoDB connection code into main server file. Please have a look at the following code:
Put following code inside connection.js file:
constdb=mongoose.createConnection('mongodb://127.0.0.1:27017/user',{useNewUrlParser:true,useUnifiedTopology:true,});db.on('error',function(error){console.log(`MongoDB :: connection ${this.name}${JSON.stringify(error)}`);db.close().catch(()=>console.log(`MongoDB :: failed to close connection ${this.name}`));});db.on('connected',function(){mongoose.set('debug',function(col,method,query,doc){console.log(`MongoDB :: ${this.conn.name}${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);});console.log(`MongoDB :: connected ${this.name}`);});db.on('disconnected',function(){console.log(`MongoDB :: disconnected ${this.name}`);});module.exports=db;
Now create another file and call it index.js and put following code inside of it:
constexpress=require('express');require('./connection');constapp=express();constport=3000;app.listen(port,()=>console.log(`App listening at http://localhost:${port}`));
To do that you have to import the file which contains the MongoDB connection code into main server file. Please have a look at the following code:
Put following code inside
connection.js
file:Now create another file and call it
index.js
and put following code inside of it:Thanks for your quick reply! I will try your suggestion