Mongoose - 仅填充返回_id而不是Object

时间:2018-06-13 03:04:08

标签: mongodb mongoose

我正在尝试建立一个计划记录两队的比赛。

MatchSchema:

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')

TeamSchema:

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
}

HomeTeam:

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

我想使用populate函数来获取匹配的完整细节。

getMatch

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`
 */
})

谢谢你们!!!“

0 个答案:

没有答案