为啥我的 Mongoose 填充请求不起作用?
Posted
技术标签:
【中文标题】为啥我的 Mongoose 填充请求不起作用?【英文标题】:Why my Mongoose populate request does not work?为什么我的 Mongoose 填充请求不起作用? 【发布时间】:2021-12-20 13:51:18 【问题描述】:在我的数据库中,我收集了 totalpoints
和以下示例文档:
"_id":
"playerId": "113069",
"tournamentId": "197831"
,
"playerName": "xyz",
"pointsTotal": 0,
"__v": 0
对于名为 teams
的其他集合之一,我定义了以下架构:
const teamsSchema = new Schema(
_id:
teamName: String,
tournamentId: String
,
tournamentName: String,
player1:
type: Schema.Types.ObjectId,
ref: 'PointTotal',
)
我在 MongoDB 的团队收藏中得到的是这个文档:
"_id":
"teamName": "BILALATI6449",
"tournamentId": "197831"
,
"tournamentName": "Amanora Cricket Championship 2021",
"player1":
"playerId": "113069",
"tournamentId": "197831"
,
"_v": 0
但是,当我执行以下代码时:
const doc = await Team.findOne(
"_id.teamName": "BILALATI6449",
"_id.tournamentId": "197831"
).populate("player1")
console.log(doc)
以下结果打印到控制台,.populate
不工作:
_id: teamName: 'BILALATI6449', tournamentId: '197831' ,
tournamentName: 'Amanora Cricket Championship 2021',
__v: 0
这是完整的文档样本表单团队集合:
"_id":
"teamName": "BILALATI6449",
"tournamentId": "197831"
,
"tournamentName": "Amanora Cricket Championship 2021",
"player1":
"playerId": "2331078",
"tournamentId": "197831"
,
"player2":
"playerId": "196713",
"tournamentId": "197831"
,
"player3":
"playerId": "113069",
"tournamentId": "197831"
,
"player4":
"playerId": "249044",
"tournamentId": "197831"
,
"player5":
"playerId": "113129",
"tournamentId": "197831"
,
"player6":
"playerId": "181056",
"tournamentId": "197831"
,
"player7":
"playerId": "658022",
"tournamentId": "197831"
,
"player8":
"playerId": "182623",
"tournamentId": "197831"
,
"player9":
"playerId": "249047",
"tournamentId": "197831"
,
"player10":
"playerId": "658053",
"tournamentId": "197831"
,
"player11":
"playerId": "658057",
"tournamentId": "197831"
,
"__v": 0
【问题讨论】:
如果你想我可以用$lookup
回答这个问题
@mohammadNaimi 是的,请回答。
【参考方案1】:
在团队集合中使用聚合
db.team.aggregate([
"$match":
"_id.teamName": "BILALATI6449",
"_id.tournamentId": "197831"
,
"$lookup":
"from": "totalpoints",
"localField": "player1.playerId",
"foreignField": "_id.playerId",
"as": "player1"
])
https://mongoplayground.net/p/nGJSZ6kJMIc
如果为您提供具有多个玩家编号的新样本数据,请使用此
db.team.aggregate([
"$match":
"_id.teamName": "BILALATI6449",
"_id.tournamentId": "197831"
,
"$addFields":
"newField":
"$filter":
"input":
"$objectToArray": "$$ROOT"
,
"as": "p",
"cond":
"$regexMatch":
"input": "$$p.k",
"regex": ".*player*."
,
"$lookup":
"from": "totalpoints",
"localField": "newField.v.playerId",
"foreignField": "_id.playerId",
"as": "players"
,
"$project":
_id: 1,
tournamentName: 1,
players: 1
])
https://mongoplayground.net/p/ctGybQzGrW7
【讨论】:
我可以将它与 findOne() mongoose 方法一起使用吗? 不,这是不同的方法await Team.aggregate
像这样
我在同一个文档中还有 10 多个播放器作为单独的对象,每个播放器指向 pointtotals 集合中的不同文档。我该如何管理它们?
提供样本完整数据
我已包含完整的示例文档。以上是关于为啥我的 Mongoose 填充请求不起作用?的主要内容,如果未能解决你的问题,请参考以下文章