node.js backend koa2 framework blog project connects to mongodb database to realize simple addition, deletion, modification and query

Required software:

vscode, official website link Download: ; (you can also use the editor you are used to)
node.js, official website link Download: ;
Mongodb, official website download link: , we can just install the community version. (mac users are advised to use brew. After all, it is convenient to install. Link to brew official website: (with process)

Run MongoDB Community Edition
To run MongoDB (i.e. mongod process) as a macOS service, issue the following command:
brew services start mongodb-community@4.4
To stop mongod running as a macOS service, use the following command as needed:
brew services stop mongodb-community@4.4
Official documents: (remember the corresponding version, mine is 4.4)
Then you can open mongodb compass to connect

mongodb compass, the official visualization tool software, can be downloaded from the official website: ;
Just install the appropriate version of your computer. After installation, directly click connect to create a database and then a collection
Generally, you can directly click next to install these. For some foreign software, you'd better not have Chinese paths in the installation directory to avoid problems.

In the last chapter, we created the project directory of koa2 with scaffolding. You can go there first< node.js back-end koa2 framework koa generator scaffold code detailed introduction to quick project creation (I)>

1. Recreate koa2 project

Re create a new koa2 project through the koa2 scaffold. You can click the link above to access it.

2. Install mongoose plug-in and xss plug-in

Click "terminal" - "new terminal" in the navigation bar at the top right of vscode, and enter: npm install mongoose xss --save

3. Create a folder and set the connection to mongodb

Enter the db folder in the root directory of the project to create mymongo JS code is as follows:

const mongoose = require('mongoose') // Introducing plug-ins

const url = 'mongodb://localhost:27017 '/ / set the link port (default)
const dbName = 'myblog' // Database name

mongoose.connect(`${url}/${dbName}`,{ // The first parameter to connect is the link port and database name
  useNewUrlParser: true, // Some configuration information
  useUnifiedTopology: true

const db = mongoose.connection // Last connection

db.on('error', err => { // Monitor for errors
db.once('open', () => { // If the listening connection is successful, print it on the console. After printing once, you can adjust the comment after knowing that the connection is successful, otherwise it will be output every time you save and start.
  console.log('mongoose Successfully started')
// db.close() / / disconnect

module.exports = mongoose // Finally return out

4. Create the models folder and set the model

Create a blog in the models folder JS, the code is as follows:

const mongoose = require('../db/mymongo') // Introduce the newly created mymongo

const BlogSchema = mongoose.Schema({ // Create collection format
  title: { // There is a title in the collection
    type: String, // Type is string
    required: true // Required options
  content: String, // There is a content of type string in the collection
  author: String
}, {timestamps: true}) // timestamps automatically adds the time value for each data addition, including the time value created and changed for the first time

const Blog = mongoose.model('blog', BlogSchema) // Then add the BlogSchema just created into mongoose Model, the first parameter 'blog' is the blog collection name of your database, and then the blog will be followed by s by default, which is equal to blogs

module.exports = Blog // Finally return out

Create folder, controller, content settings

Create a controller folder and create a blog in it JS file, the code is as follows:

const Blog = require('../models/Blog') // Introduce the Blog we just created
const xss = require('xss') // Introduce xss anti-virus tool plug-in

const getList = async (author, keyword) => { // Get blog data
  let whereObj = {} // Create a condition object. If there is a value transferred from the front end, set
  if (author) { = author}
  if (keyword) {whereObj.keyword = new RegExp(keyword)}

  return await Blog.find(whereObj).sort({_id: -1}) // Finally, find the content through the find method of Blog, and then_ id is the value of the data returned by flashback sorting. Because it is asynchronous, await can be used to wait for the data to return


const getDetail = async (id) => { // Get content
  return await Blog.findById(id) // findById method query id


const newBlog = async (newblog = {}) => { // New blog
  let { title, content, author } = newblog

  title = xss(title)
  content = xss(content)

  const blog = await Blog.create({ // The create method creates data for
  return {
    id: blog._id

const upDatablog = async (id, updatablog) => { // Update blog
  let { title, content } = updatablog
  title = xss(title)
  content = xss(content)
  const upblog = await Blog.findOneAndUpdata({ // findOneAndUpdata is to find a data and update it. The first parameter is the condition, the second parameter is the updated content, and the third parameter is the setting
    _id: id // condition
  }, { // Update content
  }, {
    new: true // Returns a new value
  return upblog? true:false // If the upblog is updated successfully and there is a value in it, it returns true

const delBlog = async (id, author) => { // Delete a data
  const delblog = await Blog.findOneAndDelete({ // The findOneAndDelete method queries a data and deletes it
    _id: id, // condition
    author // condition
  return delblog? true:false

module.exports = { // Finally, all methods are returned for routing calls.

6. Enter the routes folder and create a blog JS file

Enter the routes folder of the root directory and create a blog JS file, the code is as follows:

const router = require('koa-router')() // Route referencing kao
const { getList, getDetail, newBlog, upDatablog, delBlog } = require('../controller/blog') // Return methods about blogs

router.prefix('/api/blog') // The prefix method is the front content of each of the following routes, for example: http://localhost:3000/api/blog/list , each access route must contain / API / blog
router.get('/list', async (ctx, next) => { // The access link of the get method is: http://localhost:3000/api/blog/list
  const author = // Get the passed author value from ctx
  const keyword = ctx.query.keyword
  const dataList = await getList(author, keyword) // Call and execute getList and pass in author and keyword. Because its return value is also promise, await can also be used
  ctx.body = { // ctx. The value of body is the value returned to the front end
  	errno: 0,
  	dataList // Return the obtained data to the front end

router.get('/detail', async (ctx, next) => { // The remaining methods are basically the same. You can write by yourself
  const dataDetail = await getDetail( // The parameters passed from the id and get methods to the backend are all in CTX query
  ctx.body = {
  	errno: 0
})'/new', async (ctx, next) => { // 
  let blog = ctx.request.body // All the contents of the post request are in CTX request. body
  blog.createtime = new Date().getDate()
  const data = await newBlog(blog)
  ctx.body = {
  	errno: 0,

module.exports = router // Finally, return the route back

6. Enter app JS file

After the route is created, it needs to be in the app JS. The code is as follows:

const blogs = require('./routes/blog') // Import first.
// Then find the router and add it to the routing location
app.use(blogs.routes(), blogs.allowedMethods()) // The registration can be completed. Remember to add the location to the template.

Finally, we enter in the browser: http://localhost:3000/api/blog/list You can access the database content of mongodb.

I typed this article word by word, and I also made the picture myself. Each line of the code is basically explained, which is also written according to my understanding and thinking as a beginner. I am also watching various videos and learning progress. If I find some good ones, I will write them to impress myself. By the way, record the code, If there is something wrong, please point it out. Thank you very much!
thank you

A growing lion! Let's work together.

Keywords: node.js MongoDB Back-end

Added by Rommeo on Fri, 11 Feb 2022 08:56:16 +0200