所以这是我的模特:
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非常令人困惑,所以请原谅我,如果它显然很明显!
答案 0 :(得分:0)
在将自己沉浸在主题中之后,我可以更好地了解下面的内容:
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
对象也会收到更改!