[英]Populating Virtual Field in Mongoose
我目前正在构建一个记录扑克统计数据的应用程序。 用户创建玩家,然后用这些玩家填充游戏。
我有一个游戏 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 },
})
为了获取单个游戏的信息,我填充了对玩家的引用 -
// 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)
}
}
这很好用,例如firstPlace
填充了包含该播放器所有信息的 object。
但是,我的用户 model 上有一个虚拟字段,它可以获取用户创建的所有游戏。 下面的代码 -
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,
}
})
})
这行得通 - 但所有放置都是objectIds
而不是对象本身。 我的问题是 - 我怎样才能在这个虚拟领域填充这些对Players
的引用?
在此先感谢,我一直在努力解决这个问题!
经过多次试验和错误,我添加了这个来填充嵌套对象 -
let user = await User.findById(currentUserId)
.populate('addedPlayers')
.populate([
{
path: 'addedGames',
populate: {
path: 'firstPlace secondPlace thirdPlace fourthPlace fifthPlace sixthPlace seventhPlace eighthPlace',
},
},
])
最初我只是populate('addedGames')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.