gpt4 book ai didi

node.js - 如何在 Mongoose 中的虚拟对象中填充对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:08 25 4
gpt4 key购买 nike

我设置了一个如下所示的虚拟查询:

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 模型包含的其他字段?

最佳答案

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);

}
);

关于node.js - 如何在 Mongoose 中的虚拟对象中填充对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23737601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com