使用Node.js连接到Docker容器中的MongoDB

使用npm安装mongoDB版本5.6.0。(请注意:此为简化版翻译,并非实际的命令行指令。)

使用MongoDB软件包进行连接。

 

开发环境

image.png

目录结构

image.png

将下面的源代码写入app.js文件中。


    const express = require("express");
    const app = express();
    const port = 3000;
    const path = require("path");
    const { MongoClient } = require("mongodb");
    
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());
    
    const uri = "mongodb://admin:password@localhost:27017";
    const client = new MongoClient(uri);
    
    const options = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    };
    
    app.get("/", (req, res) => {
      res.sendFile(path.join(__dirname, "index.html"));
    });
    
    app.get("/get-profile", async (req, res) => {
      try {
        await client.connect();
        const db = client.db("user-account");
        const collection = db.collection("users");
        const result = await collection.findOne({ userid: 1 }, options);
    
        await collection.insertOne({
          userid: 2,
          name: "luigi",
        });
        res.json(result);
      } catch (error) {
        console.log(error);
      } finally {
        await client.close();
      }
    });
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`);
    });

连接URI

image.png

使用Mongo-express图形用户界面预先插入数据。

我正在用户ID为1的位置放入马里奥。

image.png

请参考此链接了解如何启动mongo-express容器。

 

直接通过浏览器进行访问。

image.png

路易吉的唱片也已经被添加进去了,对吗?

image.png

使用npm安装mongoose和mongodb

 

image.png

 

image.png
广告
将在 10 秒后关闭
bannerAds