3
7

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.

MongoDB CRUD入門 勉強ノート

3
Posted at

MongoDBとは

document database ~ NoSQL ~ と呼ばれている。
リレーショナルデータベースと異なり、json objectをmongodbに保存していくだけ、というシンプルさがある。

起動方法

$ mongod 

waiting for connections on port 27017

データーベースを使用の際は、基本的に起動したままにしておく。

終了時は必ずCtrl+Cでシャットダウンできたか確認しておくこと!

MongoDB CompassというPSequelのようなアプリケーションを入れておくと、データーベースの内容が簡単に確認できるので便利。


Mongoose

MongoDB用モデリングツール。モデルの定義、操作が可能。

npm i mongoose

Mongooseをインストール

以降はnodeを使用したケースです。

index.js
const mongoose = require('mongoose');

// localhostでの実行。Databaseを自動で作ってくれます
mongoose
  .connect('mongodb://localhost/playground', { useNewUrlParser: true })
  .then(() => console.log('Connected to MongoDB...'))
  .catch(err => console.error('Could not connect to the DB', err));

node index.jsで起動すると'Connected to MongoDB...'と接続成功のメッセージが表示される。


MongoDB接続

index.js
// Schemaの作成
const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: { type: Date, default: Date.now },
  isPublished: Boolean
});

// Model (大文字・単数)
const Course = mongoose.model('Course', courseSchema);

データー作成

index.js
async function createCourse() {
  const course = new Course({
    name: 'Node.js',
    author: 'John',
    tags: ['node', 'javascript'],
    // dateは自動で生成されるので記載なし
    isPublished: true
  });

  const result = await course.save();
  console.log(result);
}

createCourse();

注意
courseと記載がありますが、これらはサンプルです。


データー取得

index.js

// GET
async function getCourses() {
  const courses = await Course
    .find({ author: 'john', isPublished: true })
    .limit(10)
    .sort({ name: 1 })
    .select({ name: 1, tags: 1 });
  console.log(courses);
}

getCourses();


データー更新

index.js

async function updateCourse(id) {
  // idで、対象のコースを見つける
  const course = await Course.findById(id);
  if (!course) return;
  // Object
  course.isPublished = true;
  course.author = 'Another Author';

  const result = await course.save();
  console.log(result);
}

updateCourse('ここにMongoのObject Idを');

alternative
上のやり方とは別の方法で、アップデートすることも可能。

index.js
async function updateCourse(id) {
  // idで、対象のコースを見つける
  const course = await Course.update(
    { _id: id },
    {
      $set: {
        author: 'Another Author',
        isPublished: false
      }
    }
  );
  console.log(course);
}

updateCourse('ここにMongoのObject Idを');

データー削除 

index.js
async function removeCourse(id) {
  const result = await Course.deleteOne({ _id: id });
  console.log(result);
}

removeCourse('ここにMongoのObject Idを');

なおdeleteOneメソッドを使用しているがその他にもdeleteManyなど様々なメソッドがあるので、こちらのドキュメントを確認の上学んでいく!


感想

MongoDBはMEAN StackやMERN Stackと呼ばれる技術セットとして使われることが多いのでチュートリアルも充実しており、学習リソースが豊富なのが学習初期のメリットだと感じました。

誤りなどありましたらぜひコメント頂けると幸いです!

3
7
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
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?