跳到主要內容

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”的一個或多個帖子的使用者

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 之旅。保持資訊暢通,參與其中,並與其他開發者協作 我們活躍的社群。保持資訊暢通,積極參與,並與其他開發者協作。

我們真誠地重視您的參與,並期待您成為我們社群的一員!

© . This site is unofficial and not affiliated with Prisma Data, Inc.