2016-11-22 92 views
2

我已經創造了貓鼬架構這樣的虛方法執行在貓鼬的虛方法:呼叫時發現()

UserSchema.virtual('fullName').get(function() { 
return this.firstName + ' ' + this.lastName; 
}).set(function(replacedName) { 
this.set(this.firstName, replacedName); 
}); 

而且在服務器執行find()方法:

User.find({}).exec(function(error, users) { 
// I want to use virtual method for users array 
users.set('fullName', 'Name will be replaced'); 
}); 

莫非我使用虛擬方法進行數組無循環嗎? 我正在研究NodeJS和Mongoose。

+1

我覺得不能因爲貓鼬架構只適用於單一的對象,而不是數組對象。 – truonghm

回答

2

@truonghm在評論中說,沒有辦法單穩虛方法適用於以文件的數組。

你可以做什麼:


User.find({}).exec(function(error, users) { 
    // Loop on results and execute the 'set' virtual method 
    users.forEach(x => x.set('fullName', 'Name will be replaced')); 
}); 

創建模式中的一種方法,是會爲你做的工作:

Check the Query Helper part in mongoose Documentation

這將導致到:

User.getAllOverrideName(fullName) 
    .exec(function(error, users) { 

    }); 
+1

感謝您對Mongoose中Query Helper部分的建議。我以前從來不知道。 – truonghm