创建node.js应用程序及通过MongoDB执行CRUD操作的教程

278 阅读5分钟

Node.js和MongoDB教程

你好。在本教程中,我们将创建一个简单的node.js应用程序,并通过MongoDB执行CRUD操作。

node.js框架通常用于创建基于服务器的应用程序,并进一步用于向用户展示内容。

1.简介

让我们先了解一下什么是Mongo数据库并建立Node.js:

  • MongoDB是一个高性能的_NoSQL数据库_,每个数据库都有集合,而集合又有文档。每个文档都有不同的字段数量、大小和内容,并以类似JSON的格式(即二进制JSON(BSN))存储。
  • MongoDB中的文档不需要事先定义一个模式。相反,字段(即_记录_)可以随手创建
  • MongoDB中可用的数据模型允许开发人员轻松表示层次关系、存储数组和其他更复杂的结构
  • 这种NoSQL解决方案通常带有嵌入、自动分片和内置复制功能,以获得更好的可扩展性和高可用性。

1.1 设置Node.js

要在Windows上设置Node.js,你需要从这个链接下载安装程序。点击你的平台的安装程序(也包括NPM包管理器),运行安装程序,开始Node.js设置向导。按照向导的步骤操作,完成后点击 "完成"。如果一切顺利,你可以导航到命令提示符来验证安装是否成功,如图1所示。

node js mongo db tutorial - npm intallation

图 1: 验证 node 和 npm 的安装情况

2.在Docker上设置Mongo数据库

在教程的开始,我希望你已经在本地环境中建立并运行了Mongo数据库。为了方便使用,我将在Docker环境中设置它。你可以使用下面的清单文件,在几分钟内让容器启动和运行。该文件还将创建一个名为employeedb 的初始数据库。

堆栈.yml

services:
  mongodb:
    image: mongo
    container_name: mongodb
    environment:
      MONGO_INITDB_DATABASE: employeedb
    ports:
      - "27017:27017"
version: "3"

要执行或停止/删除清单文件,你可以执行以下命令。

Docker命令

-- start the container
docker-compose -f stack.yml up -d

-- stop and remove the container
docker-compose -f stack.yml down

如果一切顺利,容器将成功启动,如图2所示,你可以使用docker ps -a 命令来确认。

node js mongo db tutorial - container status

图 2: 验证容器状态

3.Node.js和MongoDB教程

为了设置应用程序,我们将需要导航到我们的项目所在的路径。对于编程的东西,我正在使用Visual Studio Code作为我的首选IDE。你可以自由选择你喜欢的IDE。

3.1 设置依赖性

导航到项目目录,运行npm init -y ,创建一个package.json 文件。这个文件保存着与项目有关的元数据,用于管理项目的依赖性、脚本、版本等。在该文件中添加以下代码,我们将指定所需的依赖性。

package.json

{
  "name": "mongodb",
  "version": "1.0.0",
  "description": "nodejs and mongodb tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "monogodb",
    "docker",
    "restapi",
    "express"
  ],
  "author": "c-danielatlas",
  "license": "MIT",
  "devDependencies": {
    "nodemon": "^2.0.11"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.13.2"
  }
}

要下载依赖项,请导航到包含该文件的目录路径,并使用npm install 命令。如果一切顺利,依赖项将被加载到node_modules 文件夹中,你就可以进行下一步了。

3.2 创建模型类

我们将在mongoose中定义Employee 模型。在根目录下创建一个名为model 的新文件夹。现在创建一个名为employee.js 的文件,内容如下。这个模型将代表mongo数据库中的一个集合。
employee.js

const mongoose = require('mongoose');

const EmployeeSchema = mongoose.Schema({
    first_name: {
        type: String
    },
    last_name: {
        type: String
    },
    email_address: {
        type: String,
        required: [true, 'Email address is required']
    },
    phone_number: {
        type: String
    },
    date_of_joining: {
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('Employees', EmployeeSchema);

3.3 创建路由文件

在根目录下创建一个名为routes 的新文件夹。现在创建一个名为employee.js 的文件,内容如下。该文件将负责处理从客户端传入的HTTP请求,并在mongoose模型的帮助下执行CRUD操作。

employee.js

const express = require('express');
const router = express.Router();
const Employee = require('../models/employee');

// submit employee details
router.post('/', (req, res) => {
    // todo - skipping request body validation for brevity

    // creating employee obj
    var employee = new Employee({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email_address: req.body.email_address,
        phone_number: req.body.phone_number
    });

    employee.save()
        .then((response) => {
            res.status(201).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// get back all employees
router.get('/', (req, res) => {
    Employee.find()
        .then(response => {
            res.status(200).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// get back a single employee
router.get('/:id', (req, res) => {
    console.log('Searching id = %s', req.params.id);
    Employee.findById(req.params.id)
        .then(response => {
            if (!response) {
                res.status(404).json({ 'message': 'Resource not found' });
            } else {
                res.status(200).json({ 'message': response });
            }
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// delete all employees
router.delete('/', (req, res) => {
    Employee.deleteMany()
        .then(response => {
            res.status(200).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// delete an employee
router.delete('/:id', (req, res) => {
    console.log('Deleting id = %s', req.params.id);

    // todo - skipping find-by-id validation for brevity

    Employee.deleteOne({ _id: req.params.id })
        .then(response => {
            res.status(200).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// update an employee
router.patch('/:id', (req, res) => {
    console.log('Updating id = %s', req.params.id);

    // todo - skipping find-by-id validation for brevity

    Employee.updateOne(
        { _id: req.params.id },
        { $set: { phone_number: req.body.phone_number } })
        .then(response => {
            res.status(204).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

module.exports = router;

3.4 设置Express webserver

在根目录下,在index.js 文件中添加以下内容。

index.js

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

// parsing request of content-type as application/json
app.use(bodyParser.json());

// import routes
const employeeRoutes = require('./routes/employees');
app.use('/employees', employeeRoutes);

// connect to db
const DB_CONNECTION = 'mongodb://localhost:27017/employeedb';
mongoose.connect(DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log('connected to db');
    }).catch(err => {
        console.log('error while connecting to db', err);
    });

// start app
const PORT = process.env.port || 3000;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

4.运行应用程序

要运行应用程序,请导航到项目目录并输入以下命令,如图2所示。如果一切顺利,应用程序将在端口号3000 上成功启动。

node js mongo db tutorial - starting the app

图 3: 启动应用程序

5.演示

你可以自由地使用postman或任何其他你选择的工具来向应用程序端点发出HTTP请求。

// submit employee details
// HTTP post
// Sample request body -
// {
//     "first_name": "John",
//     "last_name": "Doe",
//     "email_address": "john.doe@example.com",
//     "phone_number": "1234567890"
// }
http://localhost:3000/employees/

// get all employees
// HTTP get
http://localhost:3000/employees/

// get a single employee
// HTTP get
http://localhost:3000/employees/60e9b70dbe4c540fa4c3bb21

// update a single employee
// HTTP patch
http://localhost:3000/employees/60e9bea87f9c4640f0b27617

// delete a single employee
// HTTP delete
http://localhost:3000/employees/60e9bea87f9c4640f0b27617

// delete all employees
// HTTP delete
http://localhost:3000/employees/

这就是本教程的全部内容,我希望这篇文章能为你提供你想要的东西。祝你学习愉快,不要忘记分享!

6.总结

在本教程中,我们学习了如何在Docker上创建MongoDB,并通过Express网络服务器应用程序创建简单的Node.js RESTful API来执行CRUD操作。你可以从下载部分下载源代码和postman集合。

7.下载项目

这是一个在Node.js中用MongoDB创建一个CRUD应用程序的教程。

下载
你可以在这里下载这个例子的完整源代码: Node.js和MongoDB教程