简体   繁体   English

在 Mongoose 中填充虚拟字段

[英]Populating Virtual Field in Mongoose

I'm currently building an application that logs poker statistics.我目前正在构建一个记录扑克统计数据的应用程序。 Users create players and then populate games with those players.用户创建玩家,然后用这些玩家填充游戏。

I have a games model which references the players from the player model:我有一个游戏 model 引用了来自玩家 model 的玩家:

const gameSchema = new mongoose.Schema({
  firstPlace: { type: mongoose.Schema.ObjectId, ref: 'Players', required: true },
  secondPlace: { type: mongoose.Schema.ObjectId,ref: 'Players', required: true },
  thirdPlace: { type: mongoose.Schema.ObjectId, ref: 'Players', required: true },
  fourthPlace: { type: mongoose.Schema.ObjectId, ref: 'Players' },
  fifthPlace: { type: mongoose.Schema.ObjectId, ref: 'Players' },
  sixthPlace: { type: mongoose.Schema.ObjectId, ref: 'Players' },
  seventhPlace: { type: mongoose.Schema.ObjectId, ref: 'Players' },
  eighthPlace: { type: mongoose.Schema.ObjectId, ref: 'Players' },
  ninthPlace: { type: mongoose.Schema.ObjectId, ref: 'Players' },
  buyIn: { type: Number, required: true },
  firstPrize: { type: Number, required: true },
  secondPrize: { type: Number, required: true },
  thirdPrize: { type: Number, required: true },
  date: { type: String },
  notes: { type: String },
  userId: { type: mongoose.Schema.ObjectId, ref: 'Users', required: true },
})

To get the information on a single game, I populate the references to players -为了获取单个游戏的信息,我填充了对玩家的引用 -

// Get single Game
async function getSingleGame(req, res, next) {
  try {
    const { gameId } = req.params
    const foundGame = await Games.findById(gameId)
      .populate('userId')
      .populate('firstPlace')
      .populate('secondPlace')
      .populate('thirdPlace')
      .populate('fourthPlace')
      .populate('fifthPlace')
      .populate('sixthPlace')
      .populate('seventhPlace')
      .populate('eighthPlace')
      .populate('ninthPlace')
    if (!foundGame) throw new NotFound()
    return res.status(200).json(foundGame)
  } catch (err) {
    next(err)
  }
}

This works well, so for example firstPlace is populated with an object that contains all the information of that player.这很好用,例如firstPlace填充了包含该播放器所有信息的 object。

However, I have a virtual field on my user model which gets all the games that user has created.但是,我的用户 model 上有一个虚拟字段,它可以获取用户创建的所有游戏。 Code below -下面的代码 -

userSchema
  .virtual('addedGames', {
    ref: 'Games',
    localField: '_id',
    foreignField: 'userId',
  })
  .get(function (addedGames) {
    if (!addedGames) return
    return addedGames.map((game) => {
      return {
        _id: game._id,
        firstPlace: game.firstPlace,
        secondPlace: game.secondPlace,
        thirdPlace: game.thirdPlace,
        fourthPlace: game.fourthPlace,
        fifthPlace: game.fifthPlace,
        sixthPlace: game.sixthPlace,
        seventhPlace: game.seventhPlace,
        eigthPlace: game.eigthPlace,
        ninthPlace: game.ninthPlace,
        buyIn: game.buyIn,
        firstPrize: game.firstPrize,
        secondPrize: game.secondPrize,
        thirdPrize: game.thirdPrize,
      }
    })
  })

This works - but all the placings are objectIds rather than the objects themselves.这行得通 - 但所有放置都是objectIds而不是对象本身。 My question is - how can I populate these references to Players on this virtual field?我的问题是 - 我怎样才能在这个虚拟领域填充这些对Players的引用?

Thanks in advance, I've been pulling my hair out over this!在此先感谢,我一直在努力解决这个问题!

After much trial and error, I added this to populate the nested objects -经过多次试验和错误,我添加了这个来填充嵌套对象 -

let user = await User.findById(currentUserId)
  .populate('addedPlayers')
  .populate([
    {
      path: 'addedGames',
      populate: {
        path: 'firstPlace secondPlace thirdPlace fourthPlace fifthPlace sixthPlace seventhPlace eighthPlace',
      },
    },
  ])

Originally I just had populate('addedGames')最初我只是populate('addedGames')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM