How to use nodejs to implement addition, deletion, modification and query

PHPz
Release: 2023-04-05 10:07:46
Original
1473 people have browsed it

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
Copy after login

If the version information of Node.js is displayed, the installation is successful.

2. Create a project

  1. Create a project directory

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
Copy after login
  1. Initialize the project

Execute the following command in the project directory:

npm init -y
Copy after login

This command will Create a package.json file that contains project information and dependencies.

  1. Installing dependencies

Execute the following command to install the required dependencies:

npm install express body-parser mongoose --save
Copy after login

The above dependencies are:

  • express: A Node.js web framework used to simplify the development process of web applications;
  • body-parser: middleware for parsing the request body;
  • mongoose: used for operations Library for MongoDB.

3. Implement add, delete, modify and query operations

  1. Connect to MongoDB database

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!');
});
Copy after login

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.

  1. Create data model

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);
Copy after login

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.

  1. Implement the operation of adding users

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');
});
Copy after login

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.

  1. Realize the deletion operation

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);
});
Copy after login

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.

  1. Implement the modification operation

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);
});
Copy after login

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.

  1. Implement the query operation

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);
});
Copy after login

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
Copy after login

Test the above functions in Postman:

  1. Add a user:

Send POST request to http://localhost:3000/users, the request body is as follows:

{
  "name": "Tom",
  "age": 25,
  "gender": "male"
}
Copy after login
  1. Query all users:

Send GET Request to http://localhost:3000/users.

  1. Modify user information:

Send a PUT request to http://localhost:3000/users/:id, the request body is as follows:

{
  "name": "Jerry",
  "age": 30,
  "gender": "female"
}
Copy after login
  1. Delete user:

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!