1
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?

【Mongoose】モデル名とコレクション名~自動複数形変換~

Posted at

はじめに

Mongooseでは、コード上で定義したモデル名が自動的に変換され、MongoDB内部では異なる名前のコレクションとして扱われます。コレクションとは、リレーショナルデータベースにおけるテーブルに相当するものです。

モデル名とコレクション名の関係

コード上の記述

// モデル名は単数形「Cat」
const Cat = mongoose.model("Cat", catSchema);

// コード上では「Cat」を使う
await Cat.find({});
await Cat.create({});

MongoDB内部での実体

// Mongooseが自動的に「cats」コレクションに変換
db.cats.find()  // コレクション名は複数形の「cats」

実際にMongoDBを確認すると、Catという名前のコレクションは存在せず、catsという複数形のコレクションが作成されていることが分かります。

変換ルール

Mongooseは以下の手順でモデル名をコレクション名に変換します。

変換例を見てみましょう:

モデル名 コレクション名
Cat cats
Person people
Mouse mice
Product products

不規則な複数形にも対応しているのが特徴です。

MongoDBシェルでの確認方法

mongosh
use testDB
show collections
# 結果: cats

db.cats.find()  # データの取得

コレクション名を明示的に指定する

自動変換を使いたくない場合は、第3引数でコレクション名を指定できます。

const Cat = mongoose.model("Cat", catSchema, "my_cat_collection");
// コレクション名は「my_cat_collection」になる

この方法により、既存のコレクションに接続する場合や、命名規則を独自に管理したい場合に対応できます。

まとめ

Mongooseでは、コード上は単数形のモデル名を使用しますが、MongoDB内部では自動的に複数形に変換されたコレクション名として保存されます。この仕組みにより、コードの可読性を保ちながら、データベースの一般的な命名規則に従うことができるのです。

1
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
1
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?