introduce

  • This paper uses Node. js Express framework to connect cloud MongoDB Atlas to build API interface
  • This article focuses on cloud MongoDB Atlas

Create a project

  • Create a folder and open it with the VScode compiler
  • Select folder to open in terminal

Type NPM init in terminal and press Enter to confirm

Node. js Install Express Enter NPM install Express nodemon and press Enter

  • After completion, open package.json to check whether the installation is successful. The following figure shows the successful installation:

  • After the installation is successful, modify scripts to"start": "nodemon app.js"

Setting up API ports

Create the app.js file in the current directory

const express = require("express")
const app = express()

app.get('/' , (req,res) => {
  res.send("Hello World")})/ / port
app.listen(3000)
Copy the code

Enter NPM start in the terminal to open the browser and open https://localhost:3000

  • Node. js installs mongoDB in terminalctrl+cTerminate the batch operation and enter againnpm install mongooseEnter the installation

Register and create cloud MongoDB Atlas

Click on me to go to MongoDB

  • Click on the top rightTryFreeSign up for a new user and get 500 MB of free cloud data
  • Enter the email password after registration. Enter the home page
  • chooseFREEClick on theCreate a Starter Cluster
  • Select any Asian node. In this case, Taiwan
  • Give your project a name

  • Click below when you’re doneCreate Clustercreate

  • The page will jump automatically and wait 7-10 minutes for the project initialization to complete
  • The following page is displayed

  • Click on the right sideNetwork AccessClick on the item again+ ADD IP ADDRESSAdding an Access IP Address
  • I choose all IP can accessALLOW ACCESS FROM ANYWHEREreconfirmConfirm

  • You need to confirm in the registered mailbox that all IP can access the click mailbox connection to confirm

  • Confirm completion status:

  • Click on the right sideDatabase AccessThen click on+ ADD NEW USERAdding An Access User
  • Enter the user name, password, and permission

  • Click on the right sideClustersThen click onCOLLECTIONS

  • Select Add my database after filling in create create success

    Click on the right sideClustersGo back to the home page and clickCONNECTConnection data

    Click on theCopy

  • Change the password to user123 change the password admin to the name of the created database
  • Ex. :
mongodb+srv://user123:[email protected]/userDB?retryWrites=true&w=majority
Copy the code
  • Node.js installs doenv inputnpm install doenvEnter the installation
  • Add files to the root directory after the installation is complete.envWrite the URL to the database in the file
DB_CONNECTION=mongodb+srv://user123:[email protected]/userDB?retryWrites=true&w=majority
Copy the code
  • Connect to the database in app.js
const mongoose = require("mongoose")
require("dotenv/config")

mongoose.connect(process.env.DB_CONNECTION,{ useUnifiedTopology: true.useNewUrlParser: true= > {}, ()console.log("connect DB!")})Copy the code

Add, delete, change and check the database

  • Create it in the root directoryroutesFolders are created under filesposts.jsFile to deal with the unified database to add, delete, change and check the code
  • Create it in the root directorymodelsFolders are created under filesPost.jsFile to handle database key name addition

  • inposts.jsFile importmodelsUnder the filePost.js
const Post = require('.. /models/Post')
Copy the code
  • inPost.jsThe key name of the database test written to
const mongoose = require('mongoose')
const PostSchema = mongoose.Schema({
    title: {type:String.required:true
    },
    connect: {type:String.required:true
    },
    date: {type:Date.dafault: Date.now
    }
})
module.exports = mongoose.model('Posts' , PostSchema)
Copy the code
  • inapp.jsFile importroutesUnder the fileposts.js
const postRoute = require('./routes/posts')
app.use('/posts',postRoute)
Copy the code

– Add, delete, change and check code in posts.js file

const express = require("express")
const router = express.Router()
const Post = require('.. /models/Post')

// Query all data in the database
router.get('/'.async (req, res) => {
    try {
        const finePosts = await Post.find()
        res.json(finePosts)
    } catch (err) {
        res.json({ message: err })
    }
})
// Add data
router.post('/'.async (req, res) => {
    const post = new Post({
        title: req.body.title,
        connect: req.body.connect
    })
    try {
        const savePost = await post.save()
        res.json(savePost)
    } catch (err) {
        res.json({ message: err })
    }
})
// Find the data corresponding to the id
router.get('/:postId'.async (req, res) => {
    try {
        const findPost = await Post.findById(req.params.postId)
        res.json(findPost)
    } catch (err) {
        res.json({ message: err })
    }
})
// Delete data
router.delete('/:postId'.async (req, res) => {
    try {
        const removePost = await Post.remove({ _id: req.params.postId })
        res.json(removePost)
    } catch (err) {
        res.json({ message: err })
    }
})
// Modify the data
router.patch('/:postId'.async (req, res) => {
    try {
        const updatePost = await Post.updateOne({ _id: req.params.postId }, { $set: { title: req.body.title } })
        res.json(updatePost)
    } catch (err) {
        res.json({ message: err })
    }
})

module.exports = router
Copy the code
  • Note: The following dependencies also need to be installed to run properly on the server
  • Node.js installs doenv inputnpm install body-parserEnter the installation
  • Node.js installs doenv inputnpm install corsEnter the installation
  • inapp.jsThe introduction ofbody-parserwithcors
const bodyParser = require('body-parser')
const cors = require('cors')
app.use(cors())
app.use(bodyParser.json())
Copy the code

test

  • In the endnpm startStart the API
  • API testing software Postman
  • Insert data:

  • Query all data:
  • Query with id5d9caaeec6c67361e0ac3f1aData:
  • Change id for5d9caaeec6c67361e0ac3f1aData:
  • Delete the id for5d9caaeec6c67361e0ac3f1aData:

    – Browser access data:

  • Console:

Program source code

Click me to view the source code

Reprint is prohibited without the permission of the author!