呼叫时发现()
问题描述:
我已经创造了猫鼬架构这样的虚方法执行在猫鼬的虚方法:呼叫时发现()
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。
答
像@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
我觉得不能因为猫鼬架构只适用于单一的对象,而不是数组对象。 – truonghm