Mongoose实例方法丢失执行上下文

时间:2015-11-05 14:55:11

标签: node.js mongoose

const mongoose = require("mongoose"),
requiredAttr = {type: String, required: true},
employeeSchema = new mongoose.Schema({
        employeeNumber: {
            type: String,
            unique: true,
            required: true
        },
        firstName: requiredAttr,
        lastName: requiredAttr,
        image: requiredAttr
    },
    {
        timestamps: true //get createdAt, updatedAt fields
    });

employeeSchema.methods.writeThis = () => {

  console.log("doing writeThis");
  console.log(this);
};

module.exports = mongoose.model("Employee", employeeSchema);

始终收益

doing writeThis
{} //would think I would see my employee properties here

然后我通过节点命令行测试一些基本的上下文切换,发现我不能执行以下操作(如在浏览器中)

let test = { foo: "bar" };
let writeThis = () => { console.log(this); };
writeThis.apply(test); //or
writeThis.bind(test);

我错过了什么?

1 个答案:

答案 0 :(得分:1)

函数和箭头语法不能直接互换:

CoerceValueCallback

在函数语法中,调用let writeThisArrow = () => { console.log(this); }; writeThisArrow.call({stuff: "things"}); // {} function writeThisFunction() { console.log(this); } writeThisFunction.call({stuff: "things"}); // {stuff: "things"} 引用它所调用的上下文。在Arrow语法中,调用this引用它定义的上下文。如果您在mongoose中使用它,它就是文件本身的实际this。例如:

this

" exports.stuff = "things"; let writeThisArrow = () => { console.log(this); }; writeThisArrow.call(); // {stuff: "things"} "在箭头语法中是不可变的,您不能使用thisbind()call()注入上下文。在您的情况下,只需切换回标准功能声明,您就可以了。

编辑:我使用了错误的措辞。箭头语法中apply()不是 immutable ,您无法通过应用程序更改上下文。但是,可以通过编辑定义它的上下文来来更改它:

this