Combination of Express framework and Mongodb

foreword

If you open this article, it means that you have already started planning to do a project.

Here are related reference tutorials for express and mongodb. If you encounter problems, you can find the answer in it:
Express framework from entry to soil.
Introduction to Mongodb
Here is why the express framework and mongodb should be combined. The express framework does not refer to simply introducing express, but to create an express framework in combination with the express-generator tool. When the front and back ends are not separated, we can also use some lightweight databases such as lowdb, but most of the current development is the separation of the front and back ends, using js to write the back end, the most used and standardized one is express+mongodb This set of technology stacks. So this article explains this technology stack.

Finally, this article is not a hand-in-hand explanation, but a record of key steps. If you have any questions, you can find the answers in the above two articles.

Connect to the database

First import the connection database file:

module.exports = function (success, error) {
    
    
    // 导入
    const mongoose = require('mongoose');

    // 连接服务
    mongoose.connect('mongodb://127.0.0.1:27017/test');

    //设置回调
    mongoose.connection.once('open', () => {
    
    
        success()
    });

    //设置连接错误的回调
    mongoose.connection.on('error', () => {
    
    
        error()
    })

    // 设置连接关闭的回调
    mongoose.connection.on('close', () => {
    
    
        console.log('连接关闭')
    })
}

then inIntroduced in the entry file www

#!/usr/bin/env node

/**
 * Module dependencies.
 */
const db = require('../db/db')
db(() => {
    
    
  var app = require('../app');
  var debug = require('debug')('serve:server');
  var http = require('http');

  /**
   * Get port from environment and store in Express.
   */

  var port = normalizePort(process.env.PORT || '3000');
  app.set('port', port);

  /**
   * Create HTTP server.
   */

  var server = http.createServer(app);

  /**
   * Listen on provided port, on all network interfaces.
   */

  server.listen(port);
  server.on('error', onError);
  server.on('listening', onListening);

  /**
   * Normalize a port into a number, string, or false.
   */

  function normalizePort(val) {
    
    
    var port = parseInt(val, 10);

    if (isNaN(port)) {
    
    
      // named pipe
      return val;
    }

    if (port >= 0) {
    
    
      // port number
      return port;
    }

    return false;
  }

  /**
   * Event listener for HTTP server "error" event.
   */

  function onError(error) {
    
    
    if (error.syscall !== 'listen') {
    
    
      throw error;
    }

    var bind = typeof port === 'string'
      ? 'Pipe ' + port
      : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
    
    
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  }

  /**
   * Event listener for HTTP server "listening" event.
   */

  function onListening() {
    
    
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  }

})

To explain, what is passed in is a success function.

At this point, the database has been successfully connected.

Prepare model files

//导入mongoose
const mongoose = require('mongoose')

let FoodSchema = new mongoose.Schema({
    
    
    food: String,
    hot: Number
})

//创建模型对象
let FoodModel = mongoose.model('food', FoodSchema);

module.exports = FoodModel

Operate the database

Take reading documents as an example to operate the database:

I wrote a part of the data in advance, as the following table:
insert image description here
Then I read the data in the interface:

//数据库读取数据库
router.get('/foods', (req, res) => {
    
    
  FoodModel.find().then(data => {
    
    
    //设置请求头防止跨域
    res.setHeader("Access-Control-Allow-Origin", '*')
    res.send(data)
  }, err => {
    
    
    console.log(err)
  })
})

Now I use postman to test the interface and I can get it successfully:
insert image description here
Of course, I can also use axios to test: (If it fails, pay attention to the port number)

    <button class="btn">获取数据</button>
    <script>
        var btn = document.querySelector('.btn');
        btn.addEventListener('click', () => {
    
    
            axios({
    
    
                methods: "GET",
                url: 'http://127.0.0.1:3000/foods',
            }).then(res => {
    
    
                console.log(res)
            }, err => {
    
    
                console.log(err)
            })
        })

insert image description here
The remaining operations on the database can be based on the requirements, and the method in this article can be applied:
An introduction to Mongodb

postscript

The above is the combined use of Express framework and Mongodb. Subsequent articles related to this aspect will continue to be updated. Welcome to pay attention!

Guess you like

Origin blog.csdn.net/zxdznyy/article/details/131291817