MongoDB
A basis,
1. Configure the environment
Start by installing MongoDB and Node.js
NPM install mongoose
elegant mongodb object modeling for node.js
Mongoose can be understood as a tool that can connect to mongoDB database in Node
npm install mongoose --save
Copy the code
2. Easy to use
Introduce Mongoose in JS file and establish connection with database
// server.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/express-test')
Copy the code
Suppose we have multiple products and want to record each product in the database, and each product has a Tittle attribute
// server.js
// Define the product model
const Product = mongoose.model('Product'.new mongoose.Schema({
title: String,}))Copy the code
To test, use the insertMany method to insert multiple pieces of data into the database. Note that the method needs to be commented out after it is executed only once
// server.js
// Product.insertMany([
// {title: 'product 1'},
// {title: 'product 2'},
// {title: 'product 3'},
// ])
Copy the code
Use the find method to query all data in the database
// server.js
app.get('/products'.async function(req, res){
res.send(await Product.find())
})
Copy the code
The complete code is
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/express-test')
// Define the product model
const Product = mongoose.model('Product'.new mongoose.Schema({
title: String,}))// Product.insertMany([
// {title: 'product 1'},
// {title: 'product 2'},
// {title: 'product 3'},
// ])
app.get('/'.function(req, res){
res.send({ page: 'home' })
})
app.get('/about'.function(req, res){
res.send({ page: 'About Us' })
})
app.get('/products'.async function(req, res){
res.send(await Product.find())
})
app.listen(3000.() = > {
console.log('App listening on port 3000! ');
})
Copy the code
The results of
Second, the query
1. Product list page interface
Query all data
/** * find Find all data */
app.get('/products'.async function(req, res){
const data = await Product.find();
res.send(data)
})
Copy the code
Paging scenarios
/** ** limit(num) limits the number of pieces of data returned * skip and limit can be used together for paging */
app.get('/products'.async function(req, res){
const data = await Product.find().skip(1).limit(2);
res.send(data)
})
Copy the code
Specify search criteria
/** * where query criteria */
app.get('/products'.async function(req, res){
const data = await Product.find().where({
title: Products' 2 '
});
res.send(data)
})
Copy the code
The sorting
/** * sort sort 1: sort -1: sort */
app.get('/products'.async function(req, res){
const data = await Product.find().sort({_id: -1})
res.send(data)
})
Copy the code
2. Product details page interface
/** * findById is an object, not an array */
app.get('/products/:id'.async function(req, res){
const data = await Product.findById(req.params.id);
res.send(data);
})
Copy the code
New and POST requests
Suppose we want to write a new entry of product data, how do we write an interface for entry of product data?
1. REST Client plug-in
Install the REST Client plug-in in Vscode, which can initiate various HTTP requests in code
Create a new file in the root directory with the suffix HTTP, such as test.http
- Write the Request code in the file, click Send Request, you can see the Request result on the right side
- Each request requires
# # #
separate - You can use
@
Define variables{{}}
Reference variables
2. A POST request
To the test. HTTP file
POST {{uri}}products
Content-Type: Application /json {"title": "product 4"}Copy the code
3. Product input interface
To the server.js file
app.post('/products'.async function(req, res){
const data = req.body; // POST requests submitted data
const product = await Product.create(data); // Create a product
res.send(product); // Send out the product data
})
Copy the code
Because the POST request sends JSON data, it needs to be written in the server.js file
// Allow Express to process submitted JSON data
app.use(express.json())
Copy the code
Click Send Request for input product Request to obtain a piece of product dataClick Send Request of the product list Request and find that the product data has been successfully entered
Modify and PUT requests
If we want to modify a piece of product data, such as product title, how do we write a modify product data interface?
Server. The js file
/** * Modify the product data interface */
app.put('/products/:id'.async function(req, res){
/ / to find
const product = await Product.findById(req.params.id);
/ / assignment
product.title = res.body.title;
/ / save
await product.save();
/ / return
res.send(product);
})
Copy the code
To the test. HTTP file
PUT {{uri}}products/61372a06cc69aac0beb6c606
Content-Type: Application /json {"title": "product 5_ modify"}Copy the code
Click Send Request to Send the product modification Request to product 5title
Modify to “Product 5_ Modified”
DELETE and DELETE requests
Write/delete product data interface in server.js file
app.delete('/products/:id'.async function(req, res){
/ / to find
const product = await Product.findById(req.params.id);
/ / delete
await product.remove();
// Returns a status indicating that the execution succeeded
res.send({
success: true
});
})
Copy the code
To the test. HTTP file
DELETE {{uri}}products/61372a06cc69aac0beb6c606
Copy the code
Click Send Request to Send a Request to delete product 5