koa,express,node simplified connection to MongoDB

Posted by fotakis on Sat, 07 Dec 2019 11:17:58 +0100

node, express and koa connect MongoDB in the same way. We use mongoose module to connect

Read this article about connecting to mysql: koa,express,node general method to connect MySQL

Here is just a brief list of the structure of connecting MongoDB. In fact, to really understand MongoDB, you need a lot of knowledge points, such as MongoDB data types and some API operations

Briefly speaking, MongoDB's structure

Other content next time, share, connect today

Pay attention to my version

This is my catalog

Dependent version of my installation:

"dependencies": {
    "koa": "^2.6.2",
    "mongoose": "^5.3.12",

1. Connect MongoDB

// db/db.js
const mongoose = require('mongoose')

const DB_URL = 'mongodb://localhost:27017/local'


mongoose.connection.on('connected',function() {
   console.log('Mongoose connection open to '+DB_URL);
* Connection exception error database connection error
mongoose.connection.on('error',function(err) {
  console.log('Mongoose connection error: '+ err);
* disconnected the connection is abnormal
mongoose.connection.on('disconnected',function() {
  console.log('Mongoose connection disconnected');

module.exports = mongoose

2. Set the set to be operated

// db/index.js
const mongoose = require('./db')
const Schema = mongoose.Schema;

const ceshiSchema = new Schema({
  title: String,
  body: String,
  date: Date

const MyModel = mongoose.model('ceshi', ceshiSchema);

class Mongodb {
  constructor () {

// query
  query () {
     return new Promise((resolve, reject) => {
       MyModel.find({}, (err, res) => {
         if(err) {
// Preservation
  save (obj) {
     const m = new MyModel(obj)
     return new Promise((resolve, reject)=> {
       m.save((err, res) => {
         if (err) {
module.exports = new Mongodb()

Here is a simple example of query and save methods, or other methods. You can see the document specifically

3. Set up the server

// index.js
const Koa = require('koa')
const config = require('./config/default')
const ModelDb = require('./db')

const app =  new Koa()

app.use(async (ctx) => {
     let data = await ModelDb.query()
    ctx.body = data


console.log(`listening on port ${config.port}`)

4. Start the server

Open the browser, you can see the results of the query

Note: the premise is that there should be documents, that is, there should be data

First in WeChat public address: node front-end

Let's pay attention. Let's study together

Reply: 100

There are benefits.

Topics: node.js Mongoose MongoDB MySQL Database