Angular - MongoDB直接CRUD
创始人
2024-10-14 19:31:27
0

以下是一个使用Angular和MongoDB进行直接CRUD操作的解决方法,包含了代码示例:

  1. 首先,确保你已经安装了Node.js和npm。

  2. 创建一个新的Angular项目:

    ng new angular-mongodb-crud
    
  3. 进入项目目录并安装相关依赖项:

    cd angular-mongodb-crud
    npm install mongodb express body-parser
    
  4. 创建一个名为server.js的新文件,用于创建一个简单的Express服务器和MongoDB连接。

    const express = require('express');
    const mongodb = require('mongodb');
    const bodyParser = require('body-parser');
    
    const app = express();
    const mongoClient = mongodb.MongoClient;
    const mongoUrl = 'mongodb://localhost:27017';
    const dbName = 'angular-mongodb-crud';
    
    app.use(bodyParser.json());
    
    app.post('/api/create', (req, res) => {
      mongoClient.connect(mongoUrl, { useNewUrlParser: true }, (err, client) => {
        if (err) {
          console.log('Error while connecting to MongoDB:', err);
          res.status(500).json({ message: 'Error while connecting to MongoDB' });
        } else {
          const db = client.db(dbName);
          const collection = db.collection('items');
          collection.insertOne(req.body, (err, result) => {
            if (err) {
              console.log('Error while inserting item:', err);
              res.status(500).json({ message: 'Error while inserting item' });
            } else {
              res.status(200).json({ message: 'Item created successfully' });
            }
            client.close();
          });
        }
      });
    });
    
    app.get('/api/read', (req, res) => {
      mongoClient.connect(mongoUrl, { useNewUrlParser: true }, (err, client) => {
        if (err) {
          console.log('Error while connecting to MongoDB:', err);
          res.status(500).json({ message: 'Error while connecting to MongoDB' });
        } else {
          const db = client.db(dbName);
          const collection = db.collection('items');
          collection.find({}).toArray((err, items) => {
            if (err) {
              console.log('Error while reading items:', err);
              res.status(500).json({ message: 'Error while reading items' });
            } else {
              res.status(200).json(items);
            }
            client.close();
          });
        }
      });
    });
    
    app.put('/api/update/:id', (req, res) => {
      const itemId = req.params.id;
      mongoClient.connect(mongoUrl, { useNewUrlParser: true }, (err, client) => {
        if (err) {
          console.log('Error while connecting to MongoDB:', err);
          res.status(500).json({ message: 'Error while connecting to MongoDB' });
        } else {
          const db = client.db(dbName);
          const collection = db.collection('items');
          collection.updateOne({ _id: mongodb.ObjectID(itemId) }, { $set: req.body }, (err, result) => {
            if (err) {
              console.log('Error while updating item:', err);
              res.status(500).json({ message: 'Error while updating item' });
            } else {
              res.status(200).json({ message: 'Item updated successfully' });
            }
            client.close();
          });
        }
      });
    });
    
    app.delete('/api/delete/:id', (req, res) => {
      const itemId = req.params.id;
      mongoClient.connect(mongoUrl, { useNewUrlParser: true }, (err, client) => {
        if (err) {
          console.log('Error while connecting to MongoDB:', err);
          res.status(500).json({ message: 'Error while connecting to MongoDB' });
        } else {
          const db = client.db(dbName);
          const collection = db.collection('items');
          collection.deleteOne({ _id: mongodb.ObjectID(itemId) }, (err, result) => {
            if (err) {
              console.log('Error while deleting item:', err);
              res.status(500).json({ message: 'Error while deleting item' });
            } else {
              res.status(200).json({ message: 'Item deleted successfully' });
            }
            client.close();
          });
        }
      });
    });
    
    app.listen(3000, () => {
      console.log('Server listening on port 3000');
    });
    
  5. 创建一个名为item.service.ts的新文件,用于在Angular中调用服务器上的API。

相关内容

热门资讯

安装程序教程!wepoker有... 安装程序教程!wepoker有用吗,wepoker私人局辅助挂,教你教程(有挂方法),支持语音通讯、...
重大通报!wepoker有脚本... 重大通报!wepoker有脚本吗,wepoker私人局透视插件,2025新版(有挂攻略);玩家必备必...
一分钟了解!wepoker透视... 一分钟了解!wepoker透视脚本免费app,we-poker是什么软件,解密教程(有挂辅助)1、点...
关于!we-poker辅助软件... 《关于!we-poker辅助软件教程,智星德州插件,可靠教程(有挂辅助)》 we-poker辅助软件...
专业讨论!hhpoker开挂教... 专业讨论!hhpoker开挂教程,wpk透视插件,教你攻略(有挂透明)科技教程也叫必备教程,这是一款...
玩家必备科技!pokemmo脚... 1、玩家必备科技!pokemmo脚本辅助器下载,aapoker脚本怎么用,攻略方法(有挂攻略);详细...
分享实测!wepoker正确养... 分享实测!wepoker正确养号方法,wepoker有用吗,我来教教你(有挂辅助);1分钟了解详细教...
揭秘攻略!哈糖大菠萝能开挂吗,... 揭秘攻略!哈糖大菠萝能开挂吗,wepoker好友房开挂,透明挂教程(有挂教程);科技安装教程;136...
程序员教你!德州局HHpoke... 程序员教你!德州局HHpoker透视脚本,wepoker透视脚本网页,必备教程(有挂辅助)是一款可以...
玩家攻略推荐!poker wo... 玩家攻略推荐!poker world辅助,hhpkoer辅助挂是真的吗,必赢方法(有挂教程);原来确...