Express + Mongoose MongoDB Connection Configuration Sample Code
I’ll introduce sample code for MongoDB connection configuration with Express + Mongoose.
I’ll explain following the commits of Express + Mongoose demo app · Pull Request #11 · codenote-net/expressjs-sandbox that I implemented.
docker run -d \\
--name mongo4.2.2 \\
-p 27017:27017 \\
mongo:4.2.2
npm install mongoose --save
Reference commit: npm install mongoose —save | 061c68f
app.js
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGODB_URL,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
const db = mongoose.connection
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open', () => console.log('MongoDB connection successful'))
Reference commit: Setup mongoose.connect() | 28371f7
Reference articles:
Since it would be tedious to specify the environment variable MONGODB_URL every time you run node start, I added the following .envrc to manage environment variables with direnv.
.envrc
export MONGODB_URL=mongodb://localhost:27017/expressjs-sandbox
Reference commit: Add .envrc to gitignore for using direnv | fa1c8e3 Reference commit: Add .env.sample for committing to git repository | 8df02f0
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ArticleSchema = new Schema({
title: {
type: String
},
body: {
type: String
}
}, {
timestamps: true
})
mongoose.model('Article', ArticleSchema)
Reference commit: Add the article mongoose model | 3912b3a
To execute all mongoose.model() at app.js startup and auto-load models, I require() all .js files under the models directory as follows.
const fs = require('fs')
const join = require('path').join
const models = join(__dirname, 'models')
fs.readdirSync(models)
.filter(file => ~file.search(/^[^.].*\\.js$/))
.forEach(file => require(join(models, file)))
Reference commit: Bootstrap models | e9d9035
Finally, please check the sample code using Mongoose Model.find(), Model.create() from Express routes/* directly at the following URL. This is only the happy path code, and error handling is omitted.
Reference commit: (DEMO) Mongoose Model.find(), Model.create() in Express routes | 3f32fff
That’s all about configuring MongoDB connection with Express + Mongoose from the Gemba.