想象一下我有以下模型:
# MODEL A
schemaA = mongoose.Schema
_bId:
type: mongoose.Schema.Types.ObjectId
ref: "B"
# MODEL B
schemaB = mongoose.Schema
_cId:
type: mongoose.Schema.Types.ObjectId
ref: "C"
_dId:
type: mongoose.Schema.Types.ObjectId
ref: "D"
# MODEL C
schemaC = mongoose.Schema
_eId:
type: mongoose.Schema.Types.ObjectId
ref: "E"
模型 D 和 E 没有任何其他对象引用,因此为方便起见不再列出。
用所有引用填充模型“A”的最佳实践是什么?目前我按如下方式解决此任务(这是一个实例方法,因为我经常需要它):
schemaA.methods =
populateAll: (cb) ->
@
.populate
path: "_bId"
model: "B"
populate:
path: "_cId"
model: "C"
populate:
path: "_eId"
model: "E"
, (error) =>
return cb error, @ if error?
D.findById @._bId._dId
.exec (error, d) =>
return cb error, @ if error?
@._bId._dId = d
return cb error, @
这是我发现填充所有引用的唯一方法,因为在不同模型中使用多个路径填充多个路径非常困难。我已经尝试过类似下面的解决方案,但可以想象,它只会覆盖以前的人口:
@
.populate
path: "_bId"
model: "B"
populate:
path: "_cId"
model: "C"
populate:
path: "_eId"
model: "E"
.populate
path: "_bId"
model: "B"
populate:
path: "_dId"
model: "D"