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?

Mongoose Mongodbへの接続の方法

Posted at

目標 : mongooseでMongoDBへの接続ができる

データベースの操作(読み取り、書き込み、削除、更新など)はまた別の機会、ほかネット記事、ドキュメント参照のこと。

MongoDB Node.jsのインストール

MongoDBとNode.jsがインストールされていることが前提です。
(ググるかchatgptへ!)

MongoDBへの接続

まず、なんでもいいのでディレクトリを作成し、
その中にgetting-started.jsファイルを作成しましょう
(ファイル名は何でも良い)。

作成したディレクトリ内でMongooseをnpmインストールしましょう。

getting-started.jsファイルに以下のコードを書きターミナルで作成したディレクトリへ移動し
nodeコマンドを実行します。

getting-started.js
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log(`接続先データベース名: ${mongoose.connection.name}`);
  })
  .catch(err => {
    console.log('MongoDBコネクションエラー');
    console.log(err);
  })
bash
node getting-started.js

結果↓

接続先データベース名: test

公式のドキュメントの書き方。
https://mongoosejs.com/docs/index.html
async関数を用いた書き方ですね。

getting-started.js
const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/test');
  console.log(`接続先データベース名: ${mongoose.connection.name}`);
  }
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?