跳至主要内容

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.