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ù)庫 mongoose.connect('mongodb://localhost:27017/crud-api', { useNewUrlParser: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, '數(shù)據(jù)庫連接失?。?)); db.once('open', () => { console.log('數(shù)據(jù)庫連接成功!'); }); // 設(shè)置路由 app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.get('/', (req, res) => { res.send('歡迎使用CRUD API'); }); // 啟動服務(wù)器 app.listen(port, () => { console.log('服務(wù)器已啟動,端口號:' + 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'); // 查詢所有產(chǎn)品 app.get('/api/products', (req, res) => { Product.find({}, (err, products) => { if (err) { res.status(500).send('查詢數(shù)據(jù)庫出錯!'); } else { res.json(products); } }); }); // 查詢單個產(chǎn)品 app.get('/api/products/:id', (req, res) => { Product.findById(req.params.id, (err, product) => { if (err) { res.status(500).send('查詢數(shù)據(jù)庫出錯!'); } 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ù)庫出錯!'); } 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ù)庫出錯!'); } 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ù)庫出錯!'); } 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

MongoDB is suitable for handling large-scale unstructured data, and Oracle is suitable for enterprise-level applications that require transaction consistency. 1.MongoDB provides flexibility and high performance, suitable for processing user behavior data. 2. Oracle is known for its stability and powerful functions and is suitable for financial systems. 3.MongoDB uses document models, and Oracle uses relational models. 4.MongoDB is suitable for social media applications, while Oracle is suitable for enterprise-level applications.

MongoDB is suitable for unstructured data and high scalability requirements, while Oracle is suitable for scenarios that require strict data consistency. 1.MongoDB flexibly stores data in different structures, suitable for social media and the Internet of Things. 2. Oracle structured data model ensures data integrity and is suitable for financial transactions. 3.MongoDB scales horizontally through shards, and Oracle scales vertically through RAC. 4.MongoDB has low maintenance costs, while Oracle has high maintenance costs but is fully supported.

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

When installing and configuring GitLab on a CentOS system, the choice of database is crucial. GitLab is compatible with multiple databases, but PostgreSQL and MySQL (or MariaDB) are most commonly used. This article analyzes database selection factors and provides detailed installation and configuration steps. Database Selection Guide When choosing a database, you need to consider the following factors: PostgreSQL: GitLab's default database is powerful, has high scalability, supports complex queries and transaction processing, and is suitable for large application scenarios. MySQL/MariaDB: a popular relational database widely used in Web applications, with stable and reliable performance. MongoDB:NoSQL database, specializes in

MongoDB's future is full of possibilities: 1. The development of cloud-native databases, 2. The fields of artificial intelligence and big data are focused, 3. The improvement of security and compliance. MongoDB continues to advance and make breakthroughs in technological innovation, market position and future development direction.
