微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

猫鼬虚拟人的定义箭头功能与“传统”功能

如何解决猫鼬虚拟人的定义箭头功能与“传统”功能

我正在关注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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。