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 terminal
ctrl+c
Terminate the batch operation and enter againnpm install mongoose
Enter the installation
Register and create cloud MongoDB Atlas
Click on me to go to MongoDB
- Click on the top right
TryFree
Sign up for a new user and get 500 MB of free cloud data - Enter the email password after registration. Enter the home page
- choose
FREE
Click on theCreate a Starter Cluster
- Select any Asian node. In this case, Taiwan
- Give your project a name
- Click below when you’re done
Create Cluster
create
- 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 side
Network Access
Click on the item again+ ADD IP ADDRESS
Adding an Access IP Address - I choose all IP can access
ALLOW ACCESS FROM ANYWHERE
reconfirmConfirm
- 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 side
Database Access
Then click on+ ADD NEW USER
Adding An Access User - Enter the user name, password, and permission
- Click on the right side
Clusters
Then click onCOLLECTIONS
- Select Add my database after filling in create create success
Click on the right side
Clusters
Go back to the home page and clickCONNECT
Connection dataClick on the
Copy
- 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 input
npm install doenv
Enter the installation - Add files to the root directory after the installation is complete
.env
Write 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 directory
routes
Folders are created under filesposts.js
File to deal with the unified database to add, delete, change and check the code - Create it in the root directory
models
Folders are created under filesPost.js
File to handle database key name addition
- in
posts.js
File importmodels
Under the filePost.js
const Post = require('.. /models/Post')
Copy the code
- in
Post.js
The 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
- in
app.js
File importroutes
Under 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 input
npm install body-parser
Enter the installation - Node.js installs doenv input
npm install cors
Enter the installation - in
app.js
The introduction ofbody-parser
withcors
const bodyParser = require('body-parser')
const cors = require('cors')
app.use(cors())
app.use(bodyParser.json())
Copy the code
test
- In the end
npm start
Start the API - API testing software Postman
- Insert data:
- Query all data:
- Query with id
5d9caaeec6c67361e0ac3f1a
Data:
- Change id for
5d9caaeec6c67361e0ac3f1a
Data:
- Delete the id for
5d9caaeec6c67361e0ac3f1a
Data:
– Browser access data:
- Console:
Program source code
Click me to view the source code
Reprint is prohibited without the permission of the author!