Prisma+MongoDB:更新文档时如何向数组头部添加元素并排序
在Prisma中向MongoDB数组头部添加元素(替代unshift)
你可以通过以下几种方式实现往matches数组头部添加元素的需求:
方法一:使用Prisma的push操作配合position参数
Prisma的数组push操作支持each和position参数,指定position: 0就能把新元素插入到数组头部,效果等同于unshift:
await prisma.H2H.update({ where: { id: existingH2HDocument.id }, data: { matches: { push: { each: [ { matchId: editInput.matchId, leagueId: editInput.leagueId, date: editInput.date, season: editInput.season, }, ], position: 0 // 指定插入到数组的第0位(头部) } }, }, })
方法二:插入后对数组排序(按需使用)
如果你希望数组始终保持特定顺序(比如按date倒序排列),可以在插入时配合sort参数,让MongoDB自动完成排序:
await prisma.H2H.update({ where: { id: existingH2HDocument.id }, data: { matches: { push: { each: [ { matchId: editInput.matchId, leagueId: editInput.leagueId, date: editInput.date, season: editInput.season, }, ], sort: { date: -1 } // 按date字段倒序排序,最新日期排在最前 } }, }, })
兼容旧版Prisma的方案
如果你的Prisma版本不支持上述position或sort参数,可以直接执行MongoDB原生命令,通过$executeRaw实现:
await prisma.$executeRaw` update H2H set matches = $push(matches, { $each: [ { matchId: ${editInput.matchId}, leagueId: ${editInput.leagueId}, date: ${editInput.date}, season: ${editInput.season} } ], $position: 0 }) where id = ${existingH2HDocument.id} `;
内容的提问来源于stack exchange,提问作者smoothlikebutter
相关产品推荐
相关产品推荐

