问题描述
我正在关注Express教程。
我的模特:
const mongoose = require('mongoose');
const authorSchema = mongoose.Schema({
first_name: {type: String,required: true,maxlength: 100},family_name: {type: String,maxlength: 100}
});
// virtual for author's full name:
authorSchema.virtual('name').get(
() => {
return `${this.first_name} ${this.family_name}`;
}
);
// Export model:
module.exports = mongoose.model('Author',authorSchema);
请求处理程序:
exports.get_author1 = (req,res,next) => {
Author.find().then(
(results) => {
res.end(results[0].name);
// "results" returns a list of objects (each object represent an author in my db) here I am accessing the first author object of the list and using the dot notation to access its 'name' virtual.
}
)
};
生成的答案将是: undefined undefined
几个小时不了解我做错了什么之后,我将虚拟声明更改为:
authorSchema.virtual('name').get(
function() {
return `${this.first_name} ${this.family_name}`;
}
);
使用function(){}而不是()=> {},现在它可以正常工作了,并且得到了我想要的响应: Patrick Rothfuss 。
然后我的问题是传统匿名函数(function() {})和箭头功能(()=> {}),特别是在声明虚拟符号时使用它们的情况。
解决方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
如MDN所述,箭头函数没有像传统函数那样绑定到this
。