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?

【趣味エンジニア】MongoDB with mongoose の基礎

Posted at

mongoDBのインストール

今回は、mongodb-communityをhomebrewでインストールする

まずは、homebrewでmongodbのフォーミュラ(formula)をダウンロード

brew tap mongodb/brew

mongodb-communityをインストール

brew install mongodb-community

MongoDBへの接続

brew services start mongodb-community //起動
brew services stop mongodb-community //停止
brew services restart mongodb-community //再起動

データベースへのアクセス

app.js
//mongoDBへアクセス
const mongoose = require('mongoose');

//connect mongoDB by mongoose
mongoose.connect( dbConfig.url,
    {
    
    })
    .then(() => {
        console.log('MongoDBコネクションOK!!');
    })
    .catch(err => {
        console.log('MongoDBコネクションエラー!!!');
        console.log(err);
        process.exit();
    });

スキーマの作成 / モデルの作成

models / user.js
//このスキーマの作成はMongoDBの機能ではなく、mongooseの機能。
const { Schema } = mongoose;

//スキーマの作成
const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    ingredients: {
        type: [],
        default: undefined
    }
});

//モデル作成
module.exports.User = mongoose.model('User', userSchema);

ここまでで、databaseにはまだデータは作られていない。これを使ってNewでインスタンス(instance)を作成し、MongoDBへのデータの保存、取得、編集、削除などを行う。


app.js
const { User } = require('./models/user'); //User - Models

//データベースを新たに作成時など作成。
const user = new User({ email, username, ingredients: defaultIngredients });

データを扱うプログラム

CRUD - C

const newUser = new User({ email, username, ingredients: defaultIngredients });
newUser.save();

CRUD - R

const getUser1 = User.findOne();
const getUser2 = User.findById();
const getUser3 = User.findOne();

CRUD - U

await User.findByIdAndUpdate();

CRUD - D

await User.deleteOne({------});
await User.deleteMany({------});
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?