我有两个模型:
用户:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
unique: true
}
}, {
timestamps: true
})
const User = mongoose.model('User', userSchema)
module.exports = User
得分:
const mongoose = require('mongoose')
const scoreSchema = new mongoose.Schema({
score: {
type: Date,
required: true
},
playerId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
}, {
timestamps: true
})
scoreSchema.virtual('player', {
ref: 'User',
localField: 'playerId',
foreignField: '_id',
justOne: true
})
const Score = mongoose.model('Score', scoreSchema)
module.exports = Score
每个用户根据自己玩过的游戏的结果获得多个分数。
我想列出每个球员姓名的所有比分。我知道如何做到这一点:
const score = await Score.findOne()
await score.populate("player").execPopulate()
但是有多个分数却不起作用
const scores = await Score.find().sort({ score: "asc" })
await scores.populate("player").execPopulate()
TypeError: scores.populate is not a function
at router.post (/home/oem/code/exam/card-game-online/node-backend/routers/score.js:24:22)
at process._tickCallback (internal/process/next_tick.js:68:7)
如何查询所有比分及其对应的用户?也许我必须在每个比分中嵌入每个球员的名字吗?我可以填充对象数组吗?