if you are using mongoose then you can create a mongoose.js as a middleware where you initialize your connection like so:
constmongoose=require('mongoose');module.exports=function(){const{MONGO_CLUSTER_URL='mongodb://127.0.0.1',MONGO_DATABASE_NAME}=process.env;// Configure mongoose to use Promises, because callbacks are passe.mongoose.Promise=global.Promise;// Connect to the Mongo DBreturnmongoose.connect(`${MONGO_CLUSTER_URL}/${MONGO_DATABASE_NAME}`,{useCreateIndex:true,useNewUrlParser:true,useUnifiedTopology:true,});};
and then in your server.js
constmongooseMiddleware=require('./middlewares/mongoose.js');...mongooseMiddleware().then(()=>createServer(app).listen()).catch((err)=>{// an error occurred connecting to mongo!// log the error and exitconsole.error('Unable to connect to mongo.');console.error(err);});
you can call any mongoose model after this without initializing the connection again
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
if you are using mongoose then you can create a
mongoose.js
as a middleware where you initialize your connection like so:and then in your
server.js
you can call any mongoose model after this without initializing the connection again