In recent years, with the continuous development of Internet technology, the demand for web applications has also grown. In order to implement various complex operations and interactions, developers need to rely on various frameworks and platforms. The emergence of Node.js has made web application development more convenient and efficient, and its application scope has become wider and wider. This article will introduce how to use Node.js to implement add, delete, modify, and query operations, and demonstrate a simple example.
1. Installation environment
Before starting development, you need to install Node.js. It is recommended to download the latest version from the official website https://nodejs.org/en/. After the installation is successful, you can enter the following command on the command line to check whether the installation is successful:
node -v
If the version information of Node.js is displayed, the installation is successful.
2. Create a project
Create a new folder in any directory and enter the folder. You can use the following command to create and enter the project directory:
mkdir project cd project
Execute the following command in the project directory:
npm init -y
This command will Create a package.json file that contains project information and dependencies.
Execute the following command to install the required dependencies:
npm install express body-parser mongoose --save
The above dependencies are:
3. Implement add, delete, modify and query operations
Add the following code in the app.js file , to connect to the MongoDB database:
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/nodejs_demo', { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log('Database connected!'); });
In the code, first connect to the local mongodb database through the mongoose.connect() method, and then monitor the status of the database connection. If the connection is successful, print out "Database connected!" Information.
Create a new file user.js in the models folder to define the user data model. The code is as follows:
const mongoose = require('mongoose'); const schema = new mongoose.Schema({ name: String, age: Number, gender: String }); module.exports = mongoose.model('User', schema);
In the code, a data model named User is defined, which contains three attributes: name, age, and gender, which represent the user's name, age, and gender respectively.
Add the following code in the app.js file to realize the operation of adding users:
const express = require('express'); const bodyParser = require('body-parser'); const User = require('./models/user'); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.post('/users', async (req, res) => { const user = new User({ name: req.body.name, age: req.body.age, gender: req.body.gender }); await user.save(); res.send(user); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
In the code, use app. The post() method listens to the POST request of '/users', converts the parameters of the request body to generate a new User object, saves it in the database, and finally responds to the request.
Add the following code in the app.js file to implement the deletion operation of the user:
app.delete('/users/:id', async (req, res) => { const result = await User.deleteOne({ _id: req.params.id }); res.send(result); });
In the code, use app. The delete() method listens to the delete request of '/users/:id', finds the user that needs to be deleted through the user's ID, and then calls the User.deleteOne() method to delete the user from the database and respond to the request.
Add the following code in the app.js file to realize the operation of modifying the user:
app.put('/users/:id', async (req, res) => { const result = await User.updateOne({ _id: req.params.id }, { name: req.body.name, age: req.body.age, gender: req.body.gender }); res.send(result); });
In the code, use app. The put() method monitors the modification request of '/users/:id', finds the user who needs to be modified through the user's ID, and then calls the User.updateOne() method to update the user data and respond to the request.
Add the following code in the app.js file to implement the query user operation:
app.get('/users', async (req, res) => { const users = await User.find().exec(); res.send(users); });
In the code, use app. The get() method listens to the query request of '/users', searches for all users in the database through the User.find() method, and responds to the request.
4. Test
Run the following command to start the service:
node app.js
Test the above functions in Postman:
Send POST request to http://localhost:3000/users, the request body is as follows:
{ "name": "Tom", "age": 25, "gender": "male" }
Send GET Request to http://localhost:3000/users.
Send a PUT request to http://localhost:3000/users/:id, the request body is as follows:
{ "name": "Jerry", "age": 30, "gender": "female" }
Send DELETE request to http://localhost:3000/users/:id.
5. Summary
This article introduces how to create a very simple instance based on Node.js, and demonstrates how to use Express and Mongoose to implement add, delete, modify, and check operations. Of course, the examples in this article are very simple. In the actual development process, you need to pay attention to issues such as database design and request parameter verification. However, the techniques and methods described in this article can provide some help and suggestions for Node.js beginners to help them master Node.js development skills more quickly and efficiently.
The above is the detailed content of How to use nodejs to implement addition, deletion, modification and query. For more information, please follow other related articles on the PHP Chinese website!