0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nodejsから、DockerコンテナのmongoDBに接続する

Last updated at Posted at 2023-07-01

npm i mongoDB v5.6.0

mongoDB パッケージを使って接続します。

開発環境

image.png

directory storacture

image.png

app.jsに下記のソースコードを記述します。

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}`);
    });

Connection URI

image.png

Mongo-express GUIを使ってあらかじめデータを挿入します。

userid:1marioを入れています。

image.png

mongo-expressのコンテナの立ち上げ方は、こちらのリンクをご参考ください。

ブラウザからアクセスします。

image.png

luigiのレコードも追加されていますね。

image.png

npm i mongoose vs mongodb

image.png

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?