提问者:小点点

为什么这个关键字在mongoose中不起作用


架构定义

const mongoose=require('mongoose');
const Schema=mongoose.Schema;

var person = new Schema({
    name: {type : String}
})
person.pre('save', (next) => {
    console.log(' in pre function and')
    console.log(" this.name ",this.name);
    if(this.name==' '){
       // throw new console.error(' in valid name');
        console.log(err);
    }
    if(this.isNew == 'true'){
        console.log(this);
    }
    else{
        console.log(' false ' , this)
    }
    next();
})
const personModel = mongoose.model('personTable', person);
module.exports = {
    personModel
}

数据库

const mongoose= require ('mongoose');
const {personModel} = require('./schema');

mongoose.connect('mongodb://localhost/dataBase',{useNewUrlParser : true});
const db=mongoose.connection;

db.once('open',()=>{
    console.log(' connection successful ');

    const prakash = new personModel({
        name : 'prakash'
    })

    
    prakash.save((err,data)=>{
        if(err)console.error(err);
        else console.log('data saved ',data);
    })
})

在模式定义文件中,当我注销this.name时,它给出了undefined。我无法理解这个行为,我浏览了这个站点并跟踪它,但仍然无法找到识别错误https://www.codota.com/code/javascript/functions/mongoose/Schema/pre的方法


共1个答案

匿名用户

mongomongoose没有错,它是箭头函数声明。

检查你已经发布的链接。 示例中到处都有function关键字。

只需遵循您通过以下代码提供的示例即可:

Schema.pre('save', function (next) {...

您将得到以下信息

您可能想看看StackOverflow上的这些问题:

  • “箭头函数”和“函数”是否等价/可交换?
  • “this”关键字如何工作?

还有,MDN这个关于箭头函数的MDN链接。