NextJS Examples | MongoDB

NextJS Examples | Starter

NextJS Examples | Layout

NextJS Examples | Express

NextJS Examples | MongoDB

In the last post, you saw how to extend NextJS so it can be used with a custom Express server.

In this post, you'll see how to include MongoDB with a NextJS project...

Following our example...

const express     = require('express')
const next        = require('next')
const bodyParser  = require('body-parser')
const posts       = require('./api/post')
const mongoose    = require('mongoose')


//next.js configuration
const dev = process.env.NODE_DEV !== 'production'
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler()

mongoose.connect(process.env.DB_STRING, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})

nextApp.prepare().then(() => {
  const app = express()
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))
  app.use('/posts', posts)

  //catch-all for nextJS /pages
  app.get('*', (req, res) => {
    return handle(req, res)
  })
  app.listen(process.env.PORT, err => {
    if (err) throw err
    console.log('listening on port ' + process.env.port)
  })
})

That's it! In this example, we've included Mongoose, a popular ODM tool for MongoDB. By connecting to our MongoDB instance via...

mongoose.connect(process.env.DB_STRING, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})

we can share our MongoDB connection across different parts of the application...

api/post.js

const Post = require('../db/model/Post.js')
const express = require('express')
const router = express.Router()

router.get('/', async (req, res) => {
  try {
    let q = Post.find()
    q.sort({createdAt:-1})
    let posts = await q.exec()
    res.json(posts)
  } catch(e) {
    console.log(e)
    res.json({err:e})
  }
})

module.exports = router

This sample demonstrates how the same DB connection can be referenced in different files. By using Mongoose, we can reference a shared model Post across different routes using the same DB connection.

For more on Mongoose, check out the top 4 reasons to use Mongoose with MongoDB.

Your thoughts?