Hi all,
I’m working with a 3rd party course in Node.js that uses MongoDB as its database for tutorials. I’ve hit a roadblock working on integration tests because my application is connecting to MongoDB twice.
PS D:\Mosh Tutorials\Node-JS\CRUD Operations\vidly> npm run devEnv
> vidly@1.0.0 devEnv
> cross-env NODE_ENV=development NODE_PORT=3838 node index.js
{"level":"info","message":"Initializing MongoDB connection..."}
{"level":"info","message":"Initializing MongoDB connection..."}
debug
NODE_ENV: development
{"level":"info","message":"Listening on port 3838..."}
{"level":"info","message":"Listening on port 3838..."}
{"level":"info","message":"Connected to mongodb://localhost/vidly..."}
{"level":"info","message":"Connected to mongodb://localhost/vidly..."}
I understand that the application is working asynchronously, hence the weird behaviors I’m experiencing. As such, first let me show you my index.js:
const { logger } = require('./tools/logger');
const express = require('express');
const app = express();
require('./startup/logging')();
require('./startup/routes')(app);
require('./startup/db')();
require('./startup/fawn')();
require('./startup/config')();
require('./startup/validation')();
console.log(`NODE_ENV: ${process.env.NODE_ENV}`);
const port = process.env.PORT || 3838;
const server = app.listen(port, () => logger.info(`Listening on port ${port}...`));
module.exports = server;
The other text comes from db.js:
const mongoose = require('mongoose');
const { logger } = require('../tools/logger');
const config = require('config');
module.exports = function(){
try{
mongoose.connection.close();
logger.info('Initializing MongoDB connection...');
}
catch(ex){
logger.error('Starting new MongoDB connection...', ex);
}
console.log('debug');
const mongoosePath = config.get('db');
mongoose.connect(mongoosePath, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => logger.info(`Connected to ${mongoosePath}...`))
}
What’s peculiar is that, despite MongoDB being called twice, the console.log for NODE_ENV and debug are only invoked once each; I expected them to invoked twice like the rest.
There are more files that I can include in the comments upon request if need be but have left out for brevity since I only wanted to include what I believe is pertinent. How can I fix this? Thank you for your help!