メインコンテンツへスキップ

Mongoose

このページでは、Prisma ORMとMongoose APIを比較します。MongooseからPrismaへの移行方法については、こちらのガイドをご覧ください。

単一オブジェクトのフェッチ

Prisma ORM

const user = await prisma.user.findUnique({
where: {
id: 1,
},
})

Mongoose

const result = await User.findById(1)

単一オブジェクトの選択されたスカラーのフェッチ

Prisma ORM

const user = await prisma.user.findUnique({
where: {
id: 1,
},
select: {
name: true,
},
})

Mongoose

const user = await User.findById(1).select(['name'])

リレーションのフェッチ

Prisma ORM

const userWithPost = await prisma.user.findUnique({
where: {
id: 2,
},
include: {
post: true,
},
})

Mongoose

const userWithPost = await User.findById(2).populate('post')

具体的な値によるフィルタリング

Prisma ORM

const posts = await prisma.post.findMany({
where: {
title: {
contains: 'Hello World',
},
},
})

Mongoose

const posts = await Post.find({
title: 'Hello World',
})

その他のフィルター条件

Prisma ORM

Prisma ORMは、最新のアプリケーション開発で一般的に使用される追加のフィルターを多数生成します。

Mongoose

Mongooseは、フィルター条件としてMongoDBクエリセレクターを公開しています。

リレーションフィルター

Prisma ORM

Prisma ORMでは、取得するリストのモデルだけでなく、そのモデルのリレーションにも適用される条件に基づいてリストをフィルタリングできます。

たとえば、次のクエリは、タイトルに「Hello」を含む1つ以上の投稿を持つユーザーを返します。

const posts = await prisma.user.findMany({
where: {
Post: {
some: {
title: {
contains: 'Hello',
},
},
},
},
})

Mongoose

Mongooseは、リレーションフィルター専用のAPIを提供していません。クエリによって返された結果をフィルタリングする追加の手順を追加することで、同様の機能を実現できます。

ページネーション

Prisma ORM

カーソルスタイルのページネーション

const page = prisma.post.findMany({
before: {
id: 242,
},
last: 20,
})

オフセットページネーション

const cc = prisma.post.findMany({
skip: 200,
first: 20,
})

Mongoose

const posts = await Post.find({
skip: 200,
limit: 20,
})

オブジェクトの作成

Prisma ORM

const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
},
})

Mongoose

const user = await User.create({
name: 'Alice',
email: 'alice@prisma.io',
})

オブジェクトの更新

Prisma ORM

const user = await prisma.user.update({
data: {
name: 'Alicia',
},
where: {
id: 2,
},
})

Mongoose

const updatedUser = await User.findOneAndUpdate(
{ _id: 2 },
{
$set: {
name: 'Alicia',
},
}
)

オブジェクトの削除

Prisma ORM

const user = prisma.user.delete({
where: {
id: 10,
},
})

Mongoose

await User.deleteOne({ _id: 10 })

バッチ削除

Prisma ORM

const users = await prisma.user.deleteMany({
where: {
id: {
in: [1, 2, 6, 6, 22, 21, 25],
},
},
})

Mongoose

await User.deleteMany({ id: { $in: [1, 2, 6, 6, 22, 21, 25] } })

Prismaとのつながりを維持しましょう

以下とつながることで、Prismaの旅を続けましょう 活発なコミュニティ。情報を入手し、参加し、他の開発者と協力しましょう

皆様のご参加を心から歓迎し、コミュニティの一員としてお迎えできることを楽しみにしています!