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

How to develop a simple CRUD API using MongoDB

王林
王林Original
2023-09-19 12:32:001033browse

如何使用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