返回

从构建中学习:Express + MongoDB + Vue 实现 CRUD

前端

Express、MongoDB 和 Vue.js:构建全栈 CRUD 应用程序

前言

身处技术领域,持续学习是保持竞争力的不二法门。为了拓展自己的技能范围,我着手使用 Express、MongoDB 和 Vue.js 构建了一个全栈 CRUD 应用程序。在这个过程中,我将分享我的学习心得和实战经验,希望对各位有所裨益。

项目概述

我们的目标是创建一个简约实用的待办事项应用程序,用户可以添加、删除和标记待办事项。

技术栈

  • Express.js: 一款广受青睐的 Node.js 框架,适用于构建 Web 应用程序和 API。
  • MongoDB: 一个以灵活、可扩展和易用性著称的文档数据库。
  • Vue.js: 一个渐进式 JavaScript 框架,专为构建用户界面而生。其简洁、灵活性、高效性和丰富的生态系统使其备受推崇。

构建环境

首先,我们需要安装必要的软件和工具:

  • Node.js
  • MongoDB
  • Express.js
  • MongoDB Driver for Node.js
  • Vue.js

然后,新建一个项目文件夹并初始化一个 Node.js 项目。

搭建 Express 服务器

我们使用 Express.js 创建一个简单的 HTTP 服务器,负责处理 API 请求。

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

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

集成 MongoDB

接下来,我们需要连接到 MongoDB 数据库。

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;

  const db = client.db('todo-app');
  const todosCollection = db.collection('todos');

  // Create a new todo
  todosCollection.insertOne({
    title: 'Learn Express.js',
    completed: false
  }, (err, result) => {
    if (err) throw err;

    console.log('New todo created with id:', result.insertedId);
  });

  // Find all todos
  todosCollection.find({}).toArray((err, todos) => {
    if (err) throw err;

    console.log('All todos:', todos);
  });

  // Update a todo
  todosCollection.updateOne({ _id: ObjectId('62b9042849921a798698d695') }, { $set: { completed: true } }, (err, result) => {
    if (err) throw err;

    console.log('Todo updated:', result);
  });

  // Delete a todo
  todosCollection.deleteOne({ _id: ObjectId('62b9042849921a798698d695') }, (err, result) => {
    if (err) throw err;

    console.log('Todo deleted:', result);
  });

  client.close();
});

构建 Vue.js 前端

最后,我们使用 Vue.js 构建前端用户界面。

<template>
  <div>
    <input v-model="title" placeholder="Add a new todo" />
    <button @click="addTodo">Add</button>

    <ul>
      <li v-for="todo in todos" :key="todo._id">
        {{ todo.title }}
        <input type="checkbox" v-model="todo.completed" @change="updateTodo(todo)" />
        <button @click="deleteTodo(todo._id)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref } from 'vue';
import { ObjectId } from 'mongodb';

export default {
  setup() {
    const title = ref('');
    const todos = ref([]);

    const addTodo = () => {
      const todo = {
        title: title.value,
        completed: false
      };

      fetch('/api/todos', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(todo)
      })
        .then(res => res.json())
        .then(data => {
          todos.value.push(data);
          title.value = '';
        });
    };

    const updateTodo = (todo) => {
      fetch(`/api/todos/${todo._id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(todo)
      })
        .then(res => res.json())
        .then(data => {
          const index = todos.value.findIndex(t => t._id === data._id);
          todos.value[index] = data;
        });
    };

    const deleteTodo = (id) => {
      fetch(`/api/todos/${id}`, {
        method: 'DELETE'
      })
        .then(() => {
          todos.value = todos.value.filter(t => t._id !== id);
        });
    };

    useEffect(() => {
      fetch('/api/todos')
        .then(res => res.json())
        .then(data => {
          todos.value = data;
        });
    }, []);

    return {
      title,
      todos,
      addTodo,
      updateTodo,
      deleteTodo
    };
  }
};
</script>

运行项目

一切准备就绪后,我们就可以运行项目并访问 http://localhost:3000 在浏览器中查看结果了。

总结

通过这个项目,我们一步步了解了如何使用 Express、MongoDB 和 Vue.js 构建全栈 CRUD 应用程序。希望这篇指南能够对您有所启发,欢迎分享您的学习心得和体会。

常见问题解答

1. Express.js 的替代方案是什么?

  • Koa.js
  • Fastify
  • Hapi.js

2. MongoDB 的替代方案是什么?

  • PostgreSQL
  • MySQL
  • Redis

3. Vue.js 的替代方案是什么?

  • React.js
  • Angular
  • Svelte

4. 如何部署 Express、MongoDB 和 Vue.js 应用程序?

  • Heroku
  • AWS Elastic Beanstalk
  • Docker

5. 如何提高应用程序的性能?

  • 使用缓存
  • 优化数据库查询
  • 启用 gzip 压缩