5
3

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のORM:mongoose

Last updated at Posted at 2019-08-21

はじめに

MongoDBはBSON形式で、普段操作はJSON操作できており、とても簡単です。

コレクションのスキーマは定義不要で、自由にカラムも増減できるのも楽です。

しかし、RDBからの開発者だとスキーマがあったほうが理解しやすいという考えもあります。
また、スキーマがあると型は統一され、変なデータ生成はないので、チーム開発にはメリットです。

MongoDBに有名なORMはmongooseだと思います。
mongoose:https://mongoosejs.com/

インストール

npm install mongoose

App.js OR index.jsに起動追加

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});

スキーマ定義

const UsersSchema = new mongoose.Schema({
  userId: String,
  userName: String,
  age: mongoose.Schema.Types.Number,
  interests:  { type: [String] }
});

モデル生成

const Users = mongoose.model('Users', UsersSchema)

CURDメソッドを用意

exports.create = async function(user) {
  return await new Users(user).save()
}

exports.update = async function(user) {
  return await user.save()
}

exports.get = async function(id) {
  return await Users.findById(id)
}

exports.find = async function(condition, options) {
  return await Users.find(condition, null, options)
}

exports.delete = async function(id) {
  return await Users.findByIdAndRemove(id)
}

...

呼び出す例


const mongoUser = require('./users')

const user = {
   userId: "10000",
   userName: "yamata",
   age: 20,
   interests: ["サッカー", "読書"] 
}

const dbUser = await mongoUser.create(user)

注意点

モデルのデータにカスタマイズのカラムを追加するときは無視されるようです。

const users = await mongoUser.find(condition, options)

users.forEach(function(user) {
  // モデル以外のカラム情報を設定
  user.newCol = "new cloumn"
});

res.json(users)

APIでもらったレスポンスではnewColがありません。モデルに定義されていないカラムは無視されるのを注意
新規、更新の場合も定義されていないカラムは無視されます。

参考記事:https://mongoosejs.com/docs/index.html

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?