MongoDB CRUD入門 勉強ノート
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を使用したケースです。
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接続
// 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);
データー作成
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
と記載がありますが、これらはサンプルです。
データー取得
// 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();
データー更新
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
上のやり方とは別の方法で、アップデートすることも可能。
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を');
データー削除
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と呼ばれる技術セットとして使われることが多いのでチュートリアルも充実しており、学習リソースが豊富なのが学習初期のメリットだと感じました。
誤りなどありましたらぜひコメント頂けると幸いです!
Author And Source
この問題について(MongoDB CRUD入門 勉強ノート), 我々は、より多くの情報をここで見つけました https://qiita.com/Abbiscuit/items/f900b296af8d790776e3著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .