During the winter vacation, I completed a practical blog project to consolidate the nodeJS I had learned before. This project touched on some new things, some code directory of the normative structure, for future review, today to record these knowledge. The source of this project at: github.com/zhaohe6/ith…

I. Introduction to the project structure

Ii. Introduction of the third party modules used in this project

1. Body-parser parses parameters of POST requests

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))
Copy the code

The express-session module is used to configure the session. After using this module, the reQ object will have the session property, and then it can pass

req.session.username = 'itheima'
req.session.role = 'admin'
Copy the code

In this way, the flag is set so that the user who is logged in will have the username attribute, and the user who is not logged in will not have the username attribute, so that you can distinguish between logged in and not logged in users.

3. The dateFormat module is used to format dates

value.publishDate = dateFormat(value.publishDate,'yyyy-mm-dd')
Copy the code

4. Md5-node user password encryption module

md5("123123")// Returns the encrypted string
Copy the code

5. Mongoose-sex-page is used for paging query in the mongodb database

pagination(Article)
    .page(req.query.page).size(6).display(5)
    .find()
    .populate("author"."username")
    .exec((err, value) = >{
    let str = JSON.stringify(value)
    let articles = JSON.parse(str)
    let val = articles.records
    val.forEach((value) = >{
        value.publishDate = dateFormat(value.publishDate,'yyyy-mm-dd')
    })

    res.render('admin/article',{
        articles
    })

})
Copy the code

6. Mongoose provides CRUD and other methods to operate mongodb database, and returns mostly promise objects

7. The Nodemon module automatically restarts the service when the code is saved

8. Formidable for file upload requests

const form = new formidable.IncomingForm()
    // Upload the file directory
    form.uploadDir = path.join(__dirname,'.. / '.'.. / '.'public'.'uploads')
    // Whether to retain the suffix
    form.keepExtensions = true

    // Parse the form
    form.parse(req,(err,fields,files) = >{  
        Article.insertMany([{
            title: fields.title,
            author:fields.author,
            publishDate:fields.publishDate,
            cover:files.cover.path.split("public") [1].content: fields.content
        }]).then((value) = >{
            res.redirect('/admin/article')},(reason) = >{
            console.log(reason)
        })
    })
Copy the code

9. Joi module is used to write verification rules

const schema = {
        username: joi.string().min(2).max(12).required().error(new Error('Wrong username')),
        password: joi.string().regex(/ ^ [a zA - Z0-9] {30} 3 $/).required().error(new Error('Invalid password format')),
        email: joi.string().email().required().error(new Error('Email format does not meet requirements')),
        role: joi.string().valid('normal'.'admin').required().error(new Error('Role value invalid')),
        state: joi.number().valid(0.1).required().error(new Error('Status value invalid'))
   }
   joi.validate(req.body,schema).then(...)
Copy the code

Code specification

1. The files connected to the mongodb database can be imported in app.js. The content of the files connected to the database is generally as follows:

const config = require('config')
const mongoose = require('mongoose')
mongoose.connect(`mongodb://${config.get("db.user")}:${config.get('db.pwd')}@${config.get('db.host')}/${config.get('db.name')}`, {useNewUrlParser:true.useUnifiedTopology: true})
.then(() = >{
    console.log('Database connection successful')
})
.catch((reason) = >{
    console.log('Database connection failed',reason)
})
Copy the code

Introduce: require(‘./model/connect’) in app.js

4. Application of ES6 technology

1. Object deconstruction assignment can be simple to get multiple attributes in an object

const {email,password} = req.body
Copy the code

2. If the attribute value is the same as the attribute name, it can be shortened to the attribute name

5. Mongodb command

1. Start the mongo service: mongod — dbpath/home/user1 / mongo/data – the logpath/home/user1 / mongo/log/logs, fork

–fork runs as a daemon. If it has –fork, it must specify — logpath, which is where the logs will be stored.

Of course, you can also add other parameters, such as –auth, is also very common, used to add permission to the database.

2.net start mongodb Starts the mongodb service

Net stop mongodb Terminates the service

3. The mongodb function populate(” attribute name “) associates two collections