我的Mongoose架构中未定义this.name

时间:2017-12-08 02:56:10

标签: javascript node.js mongoose

我遇到了问题。在我的kittySchema Mongoose架构中。第21行。我试图从架构对象中获取this.name但我未定义。 我知道问题是什么。我正在使用箭头函数,它正在寻找箭头函数中的this.name属性,而不是箭头函数所在的对象。有没有办法解决这个问题,而不是使用普通的香草js功能? `

// Requiring Mongoose
const mongoose = require("mongoose");

const establishConnection = () => {
    // Establishing a connection to Mongoose
    mongoose.connect("mongodb://localhost/kittens");

    // Getting the Mongoose database from the pending connection
    const db = mongoose.connection;

    // Watching for Mongoose errors
    db.on("error", console.error.bind(console, "Connection error:"))
    // A connection was succesfully established
    db.once("open", () => {
        console.log("A connection was established");
        const kittySchema = mongoose.Schema({
            name: String
        });`enter code here`
        mongoose.
        kittySchema.methods.speak = () => {
            console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
        }
        const Kitten = mongoose.model("Kitten", kittySchema);
        const silence = new Kitten({ name: "Silence" });
        console.log(`A new kitty named ${silence.name} was successfully added to your database!`);
        silence.speak();
    })
}

module.exports = {
    establishConnection
}

`

2 个答案:

答案 0 :(得分:0)

嗯,正如您已经知道的那样,Arrow函数本身没有this,因此您已经遇到问题,您可以做的是将箭头函数包装在常规函数中:

var myKitty = {
  name: "Majid",
  kittyMethod : function() { 
    return (() => {
        console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
    })();
}
}
myKitty.kittyMethod ();//Mew, My Name is Majid

https://jsfiddle.net/a2ww7tby/

答案 1 :(得分:0)

  

我正在使用箭头功能,它正在寻找this.name   箭头函数中的属性而不是箭头的对象   功能在

这个假设有点不对。箭头函数在词法范围中查找值。在这种情况下,恰好是global对象。

另一方面,如果使用'常规'函数,'this'将绑定到实例化新Kitten时创建的新对象。

要解决您的问题,只需使用常规功能代替箭头功能即可。

kittySchema.methods.speak = function() {
    console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
}

无需包装箭头功能。

您可以详细了解何时不使用箭头功能here