2015-10-05 56 views
0

我想.populate具体型号,但似乎忽略了第二select命令,如果它是一个虚拟...猫鼬填充一个虚拟的而不是整个架构

// This won't work - it just returns the _id meaning it didn't populate 
.populate({ path: 'user', select: 'post' }) // Post is a : virtual('post') 
.populate('user', 'post') // Also doesn't work 

// If I manually select all the fields the virtual does, that works of course 
.populate({ path: 'user', select: '_id name image type' }) 

这里的虚拟我在用户对象上创建

// Here's the relating parts of the Model 

var UserSchema = new Schema({ 
    name : String, 
    type: {}, 
    image : String 
}); 

// Here's the virtual 
UserSchema 
.virtual('post') 
.get(function() { 
    return { 
     '_id' : this._id, 
     'name' : this.name, 
     'type' : this.type, 
     'image' : this.image 
    }; 
}); 

我必须缺少一些东西...阅读文档,一切都很好。

回答

1

猫鼬是不会承诺填充虚拟选择attribtue也docs什么也没说。看来,一般手动工作。

您可以在UserScheme上创建常量变量,这将适用于情况而不是使用虚拟。它可以返回select的字符串。

UserScheme.getPostFields = "_id name image type"; // under UserScheme 
// pass on select method 
.populate({ path: 'user', select: UserScheme.getPostFields }); 

这种方法可能很奇怪,但如果需要,您也可以动态地改变这种情况。

顺便说一下,在这种情况下,有一个适用于npm mongoose-populate-virtuals

+0

谢谢!是的,这是我意识到我可能不得不做的......我也会看看populate-virtuals插件。感谢你的帮助 –