我设置了一个如下所示的虚拟查询:
UserSchema
.virtual('user_info')
.get(function () {
return { '_id': this._id, 'username': this.username, 'admin': this.admin, 'email': this.email, 'company': this.company, 'image': this.image, 'profile': this.profile };
});
company
字段具有连接到用户的引用公司的ID。如何填充此字段以便我可以获得标题和Company
模型包含的其他字段?
答案 0 :(得分:1)
virtual
同步返回,因此您没有时间执行查询并等待getter中的结果。你可以做的是populate a regular object,在这种情况下,你的getter的返回值:
Company.populate(
someUser.user_info, // This is a plain object, not a Document.
{
path: "company",
model: "company" // If you specify the model here,
// it doesn't technically matter what
// model you use on line one...
},
function(err, user_info) {
console.log("User info with populated company", user_info);
console.log("Company name", user_info.company.name);
}
);