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 5 years have passed since last update.

node.jsからMongoDBに接続してDocumentを登録する。

Last updated at Posted at 2020-02-24

#はじめに
node.jsからMongoDBをインストールして、接続しようとしたところ、最初の接続で少し躓いたので、まとめる。

#環境

  • Windows10 Pro 64bit
  • node.js v12.14.1
  • mongodb v6.13.4
  • MongoDB 4.2.3

#環境構築
##node.jsにmongodbをインストール
以下コマンドを実行
npm install mongodb

##MongoDBをインストールする。
公式サイトからWindows用のインストーラをダウンロードしてインストールする。
実行して「次へ」ボタン押していく。

インストール後に環境変数にPathを追加する。
C:\Program Files\MongoDB\Server\4.2\bin

#MongoDB側の準備
MongoDB Compass Communityを使用して、取得したいdatabaseとDocumentを作成しておく。
左下のボタンで押下すると、Create Databaseのダイアログが出るので、入力するだけ。

image.png

#node.js側のコード
以上で準備完了。実際のサンプルコードは以下。
コメントアウト部分は旧VersionのMongoDBの記載方法です。
ネットで見つけた旧Versionの記載方法だとTypeError: db.collection is not a functionのエラーになりはまる。

node.js
const MongoClient = require("mongodb").MongoClient;
const dburl = "mongodb://localhost:27017/";
// const dburl = "mongodb://localhost:27017/myDatabase";

MongoClient.connect(dburl, (error, client) => {
  const collection = client.db('myDatabase').collection('myCollection');
  // const collection = client.collection('myCollection');

  collection
    .insertOne({_id: 1, path: "test"})
    .then(()=> console.log("success"))
    .catch(err => console.log(err));
});

#最後に
MongoDB以外にも、Electronもバージョンによって、大きく記述方法が変わっており、ネットで調べたコードでそのまま動かしてもうまく動かず躓くことが多い。。。
公式サイト読めばいいのだけど、時間かかるしで、少しジレンマを感じる今日この頃。

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?