亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Database MongoDB How to develop a simple CRUD API using MongoDB

How to develop a simple CRUD API using MongoDB

Sep 19, 2023 pm 12:32 PM
mongodb api crud

如何使用MongoDB開(kāi)發(fā)一個(gè)簡(jiǎn)單的 CRUD API

How to use MongoDB to develop a simple CRUD API

In modern web application development, CRUD (add, delete, modify, query) operations are very common and important functions one. In this article, we will introduce how to develop a simple CRUD API using MongoDB database and provide specific code examples.

MongoDB is an open source NoSQL database that stores data in the form of documents. Unlike traditional relational databases, MongoDB does not have a predefined schema, which makes data storage and query more flexible. Therefore, MongoDB is ideal for storing and processing large amounts of unstructured data.

Before developing the CRUD API, we need to ensure that MongoDB has been installed and configured correctly. You can download and install the latest version of MongoDB from the official MongoDB website and configure it according to the official guide.

Next, we will use Node.js and Express.js to develop our CRUD API. Make sure you have Node.js installed and are familiar with basic Node.js and Express.js development. let's start!

Step One: Project Initialization
First, create a new Node.js project and initialize the package.json file. Execute the following command in the command line:

$ mkdir crud-api
$ cd crud-api
$ npm init -y

This will create a new directory named crud-api and initialize a new Node.js project in it. The -y option will create a package.json file using default settings.

Step 2: Install dependencies
We will use some npm packages to help us develop the CRUD API. Execute the following command on the command line to install the dependencies:

$ npm install express body-parser mongoose

This will install express, body-parser and mongoose using npm A bag. express is a popular Node.js framework, body-parser is a middleware that parses the request body, and mongoose is an object used to interact with the MongoDB database Model Tools.

Step Three: Create Server and Routing
In the root directory of the project, create the server.js file and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
const port = 3000;

// 連接MongoDB數(shù)據(jù)庫(kù)
mongoose.connect('mongodb://localhost:27017/crud-api', { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, '數(shù)據(jù)庫(kù)連接失敗:'));
db.once('open', () => {
  console.log('數(shù)據(jù)庫(kù)連接成功!');
});

// 設(shè)置路由
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('歡迎使用CRUD API');
});

// 啟動(dòng)服務(wù)器
app.listen(port, () => {
  console.log('服務(wù)器已啟動(dòng),端口號(hào):' + port);
});

This paragraph The code first introduces the required npm package, then creates an Express application and sets the server port to 3000. After that, we use the mongoose.connect() method to connect to the MongoDB database. Please ensure that the MongoDB service is running on the default port 27017 of the local machine. Next, we set up a root route primarily for testing. Finally, we use the app.listen() method to start the server and listen on port 3000.

Step 4: Define model and routing
We will create a simple database model named product and write the corresponding CRUD routing. Add the following code in the server.js file:

const Product = require('./models/product');

// 查詢(xún)所有產(chǎn)品
app.get('/api/products', (req, res) => {
  Product.find({}, (err, products) => {
    if (err) {
      res.status(500).send('查詢(xún)數(shù)據(jù)庫(kù)出錯(cuò)!');
    } else {
      res.json(products);
    }
  });
});

// 查詢(xún)單個(gè)產(chǎn)品
app.get('/api/products/:id', (req, res) => {
  Product.findById(req.params.id, (err, product) => {
    if (err) {
      res.status(500).send('查詢(xún)數(shù)據(jù)庫(kù)出錯(cuò)!');
    } else if (!product) {
      res.status(404).send('找不到產(chǎn)品!');
    } else {
      res.json(product);
    }
  });
});

// 創(chuàng)建新產(chǎn)品
app.post('/api/products', (req, res) => {
  const newProduct = new Product(req.body);
  newProduct.save((err, product) => {
    if (err) {
      res.status(500).send('保存到數(shù)據(jù)庫(kù)出錯(cuò)!');
    } else {
      res.json(product);
    }
  });
});

// 更新產(chǎn)品
app.put('/api/products/:id', (req, res) => {
  Product.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, product) => {
    if (err) {
      res.status(500).send('更新數(shù)據(jù)庫(kù)出錯(cuò)!');
    } else if (!product) {
      res.status(404).send('找不到產(chǎn)品!');
    } else {
      res.json(product);
    }
  });
});

// 刪除產(chǎn)品
app.delete('/api/products/:id', (req, res) => {
  Product.findByIdAndRemove(req.params.id, (err, product) => {
    if (err) {
      res.status(500).send('刪除數(shù)據(jù)庫(kù)出錯(cuò)!');
    } else if (!product) {
      res.status(404).send('找不到產(chǎn)品!');
    } else {
      res.send('產(chǎn)品刪除成功!');
    }
  });
});

In this code, we first introduce the Product model, which is a model based on mongoose .Schema's simple MongoDB model. We then defined routes for querying all products, querying a single product, creating a new product, updating a product, and deleting a product. In each route, we use the corresponding mongoose method to interact with the MongoDB database and send the appropriate response based on the returned results.

Step 5: Define the model
In the root directory of the project, create a models directory and create the product.js file in it. Add the following code in the product.js file:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: String,
  price: Number,
  description: String
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;

This code defines a simple product model Product, which has a name name A string attribute named , a numeric attribute named price and a string attribute named description. Pass the productSchema model as a parameter to the mongoose.model() method and export the Product.

Step 6: Run the server
In the root directory of the project, run the server through the following command:

$ node server.js

If everything goes well, you will see success in the command line Connection to database and server started message. Now, you can access the different routes of the API in a browser or Postman, such as: http://localhost:3000/api/products.

Summary
With MongoDB and Node.js, we can easily develop a simple CRUD API. In this article, we learned how to create a simple CRUD API using a MongoDB database, Node.js, and the Express.js framework, and provided specific code examples. With a deeper understanding of MongoDB and Node.js, you can extend and customize your API according to your actual needs.

The above is the detailed content of How to develop a simple CRUD API using MongoDB. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Various ways to update documents in MongoDB collections Various ways to update documents in MongoDB collections Jun 04, 2025 pm 10:30 PM

The methods for updating documents in MongoDB include: 1. Use updateOne and updateMany methods to perform basic updates; 2. Use operators such as $set, $inc, and $push to perform advanced updates. With these methods and operators, you can efficiently manage and update data in MongoDB.

How to view all databases in MongoDB How to view all databases in MongoDB Jun 04, 2025 pm 10:42 PM

The way to view all databases in MongoDB is to enter the command "showdbs". 1. This command only displays non-empty databases. 2. You can switch the database through the "use" command and insert data to make it display. 3. Pay attention to internal databases such as "local" and "config". 4. When using the driver, you need to use the "listDatabases()" method to obtain detailed information. 5. The "db.stats()" command can view detailed database statistics.

Commands and parameter settings for creating collections in MongoDB Commands and parameter settings for creating collections in MongoDB May 15, 2025 pm 11:12 PM

The command to create a collection in MongoDB is db.createCollection(name, options). The specific steps include: 1. Use the basic command db.createCollection("myCollection") to create a collection; 2. Set options parameters, such as capped, size, max, storageEngine, validator, validationLevel and validationAction, such as db.createCollection("myCappedCollection

Operation commands to sort documents in MongoDB collection Operation commands to sort documents in MongoDB collection Jun 04, 2025 pm 10:27 PM

In MongoDB, you can use the sort() method to sort documents in a collection. 1. Basic usage: Sort by specifying fields and sorting order (1 is ascending and -1 is descending), such as db.products.find().sort({price:1}). 2. Advanced usage: It can be sorted according to multiple fields, such as db.products.find().sort({category:1,price:-1}). 3. Performance optimization: Using indexing, avoiding oversorting and paging sorting can improve efficiency, such as db.products.createIndex({price:1}) and db.products.f

What is GridFS, and when should it be used for storing large binary files in MongoDB? What is GridFS, and when should it be used for storing large binary files in MongoDB? Jun 06, 2025 am 10:50 AM

GridFS is a tool in MongoDB for storing and retrieving files with a size limit of more than 16MBBSON. 1. It divides the file into 255KB blocks, stores them in the fs.chunks collection, and saves the metadata in the fs.files collection. 2. Suitable situations include: more than 16MB of files, the need to manage files and metadata uniformly, access to specific parts of the file, and using MongoDB without introducing external storage systems. 3. GridFS is automatically stored in chunks when uploading, reorganizes files in order when reading, and supports custom metadata and multi-version storage. 4. Alternative solutions include: storing the file path in MongoDB and actually storing it in the file system,

Commands and precautions for creating databases in MongoDB Commands and precautions for creating databases in MongoDB Jun 04, 2025 pm 10:39 PM

There is no explicit "CREATEDATABASE" command in MongoDB, the database is created when the data is first inserted. 1. Use "usemydb" to switch to the database. 2. Insert the document, such as "db.users.insertOne({name:'JohnDoe',age:30})". Notes include: databases and collections are created when data is first inserted, with strict restrictions on the name, and permission management, data consistency, performance optimization and backup recovery should be considered.

Operation commands to rename MongoDB collections Operation commands to rename MongoDB collections Jun 04, 2025 pm 10:36 PM

The reasons for renaming a collection in MongoDB include code refactoring and performance optimization by using the renameCollection command. Notes include: 1. Locking the database, 2. Automatically renaming the index, 3. Update related references. Best practice suggestions: 1. Select low peak operation, 2. Back up data, 3. Verify in the test environment first. Renaming collections requires careful handling to ensure system performance and stability.

Implementation method for pagination querying documents in MongoDB collection Implementation method for pagination querying documents in MongoDB collection May 15, 2025 pm 11:00 PM

In MongoDB, pagination query can be implemented through skip() and limit() methods. 1. Use skip(n) to skip the first n documents, limit(m) to return m documents. 2. During optimization, range query can be used instead of skip() and the results can be cached to improve performance.

See all articles