2015-10-05 70 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插件。感謝你的幫助 –