search
HomeDatabaseMongoDBHow to develop a simple CRUD API using MongoDB

How to develop a simple CRUD API using MongoDB

Sep 19, 2023 pm 12:32 PM
mongodbapicrud

如何使用MongoDB开发一个简单的 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数据库
mongoose.connect('mongodb://localhost:27017/crud-api', { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, '数据库连接失败:'));
db.once('open', () => {
  console.log('数据库连接成功!');
});

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

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

// 启动服务器
app.listen(port, () => {
  console.log('服务器已启动,端口号:' + 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');

// 查询所有产品
app.get('/api/products', (req, res) => {
  Product.find({}, (err, products) => {
    if (err) {
      res.status(500).send('查询数据库出错!');
    } else {
      res.json(products);
    }
  });
});

// 查询单个产品
app.get('/api/products/:id', (req, res) => {
  Product.findById(req.params.id, (err, product) => {
    if (err) {
      res.status(500).send('查询数据库出错!');
    } else if (!product) {
      res.status(404).send('找不到产品!');
    } else {
      res.json(product);
    }
  });
});

// 创建新产品
app.post('/api/products', (req, res) => {
  const newProduct = new Product(req.body);
  newProduct.save((err, product) => {
    if (err) {
      res.status(500).send('保存到数据库出错!');
    } else {
      res.json(product);
    }
  });
});

// 更新产品
app.put('/api/products/:id', (req, res) => {
  Product.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, product) => {
    if (err) {
      res.status(500).send('更新数据库出错!');
    } else if (!product) {
      res.status(404).send('找不到产品!');
    } else {
      res.json(product);
    }
  });
});

// 删除产品
app.delete('/api/products/:id', (req, res) => {
  Product.findByIdAndRemove(req.params.id, (err, product) => {
    if (err) {
      res.status(500).send('删除数据库出错!');
    } else if (!product) {
      res.status(404).send('找不到产品!');
    } else {
      res.send('产品删除成功!');
    }
  });
});

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
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
MongoDB's Purpose: Flexible Data Storage and ManagementMongoDB's Purpose: Flexible Data Storage and ManagementMay 09, 2025 am 12:20 AM

MongoDB's flexibility is reflected in: 1) able to store data in any structure, 2) use BSON format, and 3) support complex query and aggregation operations. This flexibility makes it perform well when dealing with variable data structures and is a powerful tool for modern application development.

MongoDB vs. Oracle: Licensing, Features, and BenefitsMongoDB vs. Oracle: Licensing, Features, and BenefitsMay 08, 2025 am 12:18 AM

MongoDB is suitable for processing large-scale unstructured data and adopts an open source license; Oracle is suitable for complex commercial transactions and adopts a commercial license. 1.MongoDB provides flexible document models and scalability across the board, suitable for big data processing. 2. Oracle provides powerful ACID transaction support and enterprise-level capabilities, suitable for complex analytical workloads. Data type, budget and technical resources need to be considered when choosing.

MongoDB vs. Oracle: Exploring NoSQL and Relational ApproachesMongoDB vs. Oracle: Exploring NoSQL and Relational ApproachesMay 07, 2025 am 12:02 AM

In different application scenarios, choosing MongoDB or Oracle depends on specific needs: 1) If you need to process a large amount of unstructured data and do not have high requirements for data consistency, choose MongoDB; 2) If you need strict data consistency and complex queries, choose Oracle.

The Truth About MongoDB's Current SituationThe Truth About MongoDB's Current SituationMay 06, 2025 am 12:10 AM

MongoDB's current performance depends on the specific usage scenario and requirements. 1) In e-commerce platforms, MongoDB is suitable for storing product information and user data, but may face consistency problems when processing orders. 2) In the content management system, MongoDB is convenient for storing articles and comments, but it requires sharding technology when processing large amounts of data.

MongoDB vs. Oracle: Document Databases vs. Relational DatabasesMongoDB vs. Oracle: Document Databases vs. Relational DatabasesMay 05, 2025 am 12:04 AM

Introduction In the modern world of data management, choosing the right database system is crucial for any project. We often face a choice: should we choose a document-based database like MongoDB, or a relational database like Oracle? Today I will take you into the depth of the differences between MongoDB and Oracle, help you understand their pros and cons, and share my experience using them in real projects. This article will take you to start with basic knowledge and gradually deepen the core features, usage scenarios and performance performance of these two types of databases. Whether you are a new data manager or an experienced database administrator, after reading this article, you will be on how to choose and use MongoDB or Ora in your project

What's Happening with MongoDB? Exploring the FactsWhat's Happening with MongoDB? Exploring the FactsMay 04, 2025 am 12:15 AM

MongoDB is still a powerful database solution. 1) It is known for its flexibility and scalability and is suitable for storing complex data structures. 2) Through reasonable indexing and query optimization, its performance can be improved. 3) Using aggregation framework and sharding technology, MongoDB applications can be further optimized and extended.

Is MongoDB Doomed? Dispelling the MythsIs MongoDB Doomed? Dispelling the MythsMay 03, 2025 am 12:06 AM

MongoDB is not destined to decline. 1) Its advantage lies in its flexibility and scalability, which is suitable for processing complex data structures and large-scale data. 2) Disadvantages include high memory usage and late introduction of ACID transaction support. 3) Despite doubts about performance and transaction support, MongoDB is still a powerful database solution driven by technological improvements and market demand.

The Future of MongoDB: A Look at its ProspectsThe Future of MongoDB: A Look at its ProspectsMay 02, 2025 am 12:08 AM

MongoDB'sfutureispromisingwithgrowthincloudintegration,real-timedataprocessing,andAI/MLapplications,thoughitfaceschallengesincompetition,performance,security,andeaseofuse.1)CloudintegrationviaMongoDBAtlaswillseeenhancementslikeserverlessinstancesandm

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools