【问题标题】:Populate a nested ObjectRef填充嵌套的 ObjectRef
【发布时间】:2014-06-12 19:15:34
【问题描述】:

这是我的模型:

CompetitionSchema = new Mongoose.Schema
name :
  type : String
  required : true
required_teams :
  type : Number
teams : [
  _team :
    type : Mongoose.Schema.ObjectId
    ref : 'teams'
  weight :
    type : Number
    min : 0
]

我希望能够填充竞赛对象以访问competition.teams[0]._team._id,为此我尝试了以下操作:

  models('Competition')
  .findById id
  .populate('teams._team')
  .exec (error, competition) ->
    if error || !competition
      error_callback error
    else
      success_callback competition

但是这没有任何效果。我也试过:

  models('Competition')
  .findById id
  .exec (error, competition) ->
    if error || !competition
      error_callback error
    else
      options = [
        path : 'teams._team'
        model : 'teams'
      ]
      models('Competition')
      .populate(
        competition
      , options
      , (error, competition) ->
          if error || !competition
            error_callback competition
         else
            success_callback competition
      )

也没有效果。我觉得API documentation for Model.populate 很混乱,所以如果很明显,请原谅!

【问题讨论】:

    标签: coffeescript mongoose populate


    【解决方案1】:

    好吧,在我把自己沉浸在这个话题上之后,我终于来到了下面:

      models('Competition')
      .findById id
      .exec (error, competition) ->
        if error || !competition
          error_callback error
        else
          options = [
            path : '_team'
            model : 'teams'
          ]
          models('Team')
          .populate(
            competition.teams
          , '_team'
          , (error, competition_teams) ->
              if error || !competition_teams
                error_callback competition
             else
                success_callback competition
          )
    

    归结为:而不是调用

    Competition.populate(competition, { path : 'teams._team' } , callback);
    

    我现在打电话:

    Team.populate(competition.teams, '_team', callback);
    

    这样做的好处是修改competition.teams 数组而不是返回一个副本,所以原来的competition 对象也会收到更改!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 2018-01-20
      • 2013-03-16
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多