跳到主要内容

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: '[email protected]',
},
})

Mongoose

const user = await User.create({
name: 'Alice',
email: '[email protected]',
})

更新对象

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