首页 > 解决方案 > Mongoose - 仅填充返回 _id 而不是对象

问题描述

我正在尝试建立一个时间表来记录两支球队的比赛。

匹配架构:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let MatchSchema = {
 MatchID: {
  type: Number,
  unique: true,
  required: true
 },
 HomeTeam: {
  type: Schema.Types.ObjectId,
  ref: 'Team',
 },
 AwayTeam: {
  type: Schema.Types.ObjectId,
  ref: 'Team',
 }
}
MatchSchema = mongoose.Schema(MatchSchema)

module.exports = mongoose.model('Match', MatchSchema, 'matches')

团队架构:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let TeamSchema = {
 TeamName: {
  type: String,
  required: true,
 }
}
TeamSchema = mongoose.Schema(TeamSchema)

module.exports = mongoose.model('Team', TeamSchema, 'matches')

这是一场比赛,也是球队的记录。

匹配:

{
 _id: "5b2084a926ca2f7f7f47a083",
 MatchID: 127299,
 HomeTeam: "5b2084a926ca2f7f7f479ff3",
 AwayTeam: "5b2084a926ca2f7f7f479fed",
 __v: 0
}

主队:

{
 _id: "5b2084a926ca2f7f7f479ff3",
 TeamName: "I am a Home Team",
 __v: 0
}

我想使用填充函数来获取比赛的全部细节。

获取匹配

const Match = require('./schema/module/match')
Match.findOne({}).populate('Team').exec((err, match) {
 console.log(match)
 /* This is the result, it return the _id of those team instead of its object:
  {
   _id: "5b2084a926ca2f7f7f47a083",
   MatchID: 127299,
   HomeTeam: "5b2084a926ca2f7f7f479ff3",
   AwayTeam: "5b2084a926ca2f7f7f479fed",
   __v: 0
  }
 */
 /*
  If I call match.populated('Team'), it showed an error with `match.populated is not a function`
 */
})

感谢你们!!!

标签: mongodbmongoose

解决方案


推荐阅读