Node learning notes optimization crud addition, deletion, modification and query

Keywords: Front-end Mongoose MongoDB Database Windows

This article combines the previous< Node learning notes Mongodb and Mongoose >Yes curd example Optimize

MongoDB installation

Download address of installation file:[ https://www.mongodb.com/download-center/community]

To install MongoDB on Windows: https://www.runoob.com/mongodb/mongodb-window-install.html

Special attention should be paid during the installation process. The default check before Install MongoDB Compass should be cancelled

You can use the mongod --version command to view the MongoDB version. If the version number output is normal, the installation is completed

Mongoose installation and configuration

npm install mongoose

Optimize student.js file

With the help of Mongoose, data addition, deletion, modification and query can be greatly simplified

  • First, configure Mongoose

    var mongoose = require('mongoose'); // Introducing mongoose
    mongoose.connect('mongodb://localhost/test '); / / connect to mongodb database through mongoose
    
  • Secondly, design Schema data structure

    var mongoose = require('mongoose'); // Introducing mongoose
    mongoose.connect('mongodb://localhost/test '); / / connect to mongodb database through mongoose
    
    // Design data structure
    var Schema = mongoose.Schema
    var studentData = new Schema({ // Instantiate Schema
        name: { // full name
            type: String, // Data type String
            required: true // Data is required
        },
        gender: { // Gender
            type: Number, // Data type Number
            default: 0, // Data defaults
            enum: [0, 1] // Enumerable data
        },
        age: { // Age
            type: Number // Data type Number
        },
    })
    
  • Finally, export students

    module.exports= mongoose.model('Student', studentData)
    // Save data in Mongodb database Student collection
    // Export Mongodb data
    

So far, student.js is optimized

Optimize router.js file

For the router.js file, we only need to call the add, delete, modify and query API s provided by mongoose

The code is as follows:

var Student = require('./student') // Introduce student.js (the student module is dedicated to processing data)

var express = require('express') // Introducing express
var router = express.Router() // Create routing container

// Hang all routes in the router routing container
router.get('/', function (req, res) { // Render student list page
	// . find() is used to query all data from the database and receive a function parameter
    // function (err, students) receives two parameters, one is the error information, the other is the queried data students
    Student.find(function (err, students) {
        if (err) { // If the route jump is wrong, Server error will be thrown with status code of 500
            return res.status(500).send('Server error.')
        }
        res.render('index.html', { // Response back to student list page
            students: students
        })
    })
})

router.get('/new', function (req, res) { // Render add student page
    res.render('new.html')
})

router.post('/new', function (req, res) { // Process add students
    // new Student(req.body) create a new data
    // . save is used to add data to the database and receive a function parameter
    // The function (err) parameter is used to receive error messages
    new Student(req.body).save(function (err) {
        if (err) { // If the route jump is wrong, Server error will be thrown with status code of 500
            return res.status(500).send('Server error.')
        }
        res.redirect('/') // Page redirection back to home page
    })
})

router.get('/edit', function (req, res) { // Render edit student page
    // . findById() is used to query a piece of data according to id and receive two parameters, one is matching data and the other is function
    // The function (err, student) receives two parameters, one is error information, the other is query data result
    // req.query.id.replace(/"/g," ') is the data ID to be queried. Use. Replace to convert the ID string to a number type
    Student.findById(req.query.id.replace(/"/g, ''), function (err, student) {
        if (err) { // If the route jump is wrong, Server error will be thrown with status code 500
            return res.status(500).send('Server error.')
        }
        res.render('edit.html', { // Response back to edit student page
            student: student
        })
    })
})

router.post('/edit', function (req, res) { // Dealing with editing students
    // . findByIdAndUpdate() is used to update data according to id and receive three parameters, one is matching data, the other is data to be replaced, and the third is function
    // function (err) function receives error message
    // req.body.id.replace(/"/g," ') is the data ID to be queried. Use. Replace to convert the ID string to a number type
    var id = req.body.id.replace(/"/g, '')
    Student.findByIdAndUpdate(id, req.body, function (err) {
        if (err) { // If the route jump is wrong, Server error will be thrown with status code of 500
            return res.status(500).send('Server error.')
        }
        res.redirect('/') // Page redirection back to home page
    })
})

router.get('/students/delete', function (req, res) { // Process delete student
    // . findByIdAndRemove() is used to delete the corresponding data according to the id and receive two parameters, one is matching data and the other is function
    // function (err) function receives error message
    // req.body.id.replace(/"/g," ') is the data ID to be queried. Use. Replace to convert the ID string to a number type
    var id = req.query.id.replace(/"/g, '')
    Student.findByIdAndRemove(id, function (err) {
        if (err) { // If the route jump is wrong, Server error will be thrown with status code of 500
            return res.status(500).send('Server error.')
        }
        res.redirect('/') // Page redirection back to home page
    })
})

module.exports = router // Export router

Article synced to my personal blog:< Node learning notes optimization crud addition, deletion, modification and query>

Reference:

This article is based on the platform of blog one article multiple sending OpenWrite release!

Posted by bashaash on Wed, 18 Dec 2019 14:12:30 -0800