跳到主要內容

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] } })