我有一个需要填充的大型嵌套文档。
var PortfolioSchema = new Schema({
bonds : {
percentage : Number,
USA : {
percentage : Number,
treasury : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
},
municipal : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
},
corporate : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
}
},
international : {
percentage : Number,
developed : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
},
emergent : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
}
}
},
stocks : {
percentage : Number,
USA : {
percentage : Number,
largeCaps : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
},
mediumCaps : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
},
smallCaps : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
}
},
international : {
percentage : Number,
developed : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
},
emergent : {
percentage : Number,
securities : [ {
percentage : Number,
info : { type: ObjectId, ref: 'security' }
} ]
}
}
},
_goal : { type: ObjectId, ref: 'goal' },
createdAt : { type: Date, default: Date.now },
updatedAt : { type: Date, default: Date.now }
});
如何在所有这些字段中填充security
?我已尝试过以下代码,但它无法正常使用。
Portfolio
.findById(req.params.portfolio_id)
.populate("security")
.exec(function (err, portfolio) {
if (err) {
return res.status(404).json("Portfolio not found.");
}
res.render('portfolios/show.ejs', {
portfolio: portfolio
});
});
答案 0 :(得分:0)
我只是想通了......我所要做的就是填充每一个引用的字段:
Portfolio
.findById(req.params.portfolio_id)
.populate("bonds.USA.treasury.securities.info")
.populate("bonds.USA.municipal.securities.info")
.populate("bonds.USA.corporate.securities.info")
.populate("bonds.international.developed.securities.info")
.populate("bonds.international.emergent.securities.info")
.populate("stocks.USA.largeCaps.securities.info")
.populate("stocks.USA.mediumCaps.securities.info")
.populate("stocks.USA.smallCaps.securities.info")
.populate("stocks.international.developed.securities.info")
.populate("stocks.international.emergent.securities.info")
.exec(function (err, portfolio) {
if (err) {
return res.status(404).json("Portfolio not found.");
}
res.render('portfolios/show.ejs', {
portfolio: portfolio
});
});