Express + Mongoose MongoDB Connection Configuration Sample Code
I’ll introduce sample code for MongoDB connection configuration with Express + Mongoose.
Background
I’ll explain following the commits of Express + Mongoose demo app · Pull Request #11 · codenote-net/expressjs-sandbox that I implemented.
[Prerequisites] Node.js, MongoDB, and library versions
- Node.js 12.14.0
- Express 4.17.1
- Mongoose 5.8.3
- MongoDB 4.2.2
MongoDB started with Docker
docker run -d \\
--name mongo4.2.2 \\
-p 27017:27017 \\
mongo:4.2.2
Sample Code for Connecting to MongoDB with Express + Mongoose
Install Mongoose
npm install mongoose --save
Reference commit: npm install mongoose —save | 061c68f
MongoDB Connection Configuration with Mongoose
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:
Set Environment Variable MONGODB_URL with .envrc
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
Define Mongoose Schema and Model
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
Mongoose Models Auto-loading Configuration
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
Using Mongoose Model.find(), Model.create() in Express
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.