如何在Mongoose中填充虚拟内的对象

我已经设置了一个虚拟查询,如下所示:

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领域具有与用户连接的参考公司的标识。 我怎样才能使它填充这个领域,以便我可以得到标题和其他领域Company模型包含?

一个virtual同步返回,所以你没有时间去执行一个查询,并等待getter的结果。 你可以做的是填充一个常规的对象 ,在这种情况下,你的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); } );