跳到主要内容

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 之旅。保持信息畅通,参与其中,与其他开发者协作

我们非常珍视您的参与,并期待您成为我们社区的一员!