Mongoose 预保存 binding/this 关键字无效
Mongoose pre-save binding/this keyword is not working
架构定义
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
我无法理解这种行为,我已经经历了 this site 并遵循了它,但仍然找不到识别错误的方法。
mongo
或者mongoose
都没有错,是箭头函数声明
勾选link that you have already posted。示例中到处都有 function
关键字。
只需按照您通过此代码提供的示例进行操作即可:
Schema.pre('save', function (next) {...
你会得到以下内容
你可能想看看 Whosebug 上的这个问题:
- How does the "this" keyword work?
架构定义
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
我无法理解这种行为,我已经经历了 this site 并遵循了它,但仍然找不到识别错误的方法。
mongo
或者mongoose
都没有错,是箭头函数声明
勾选link that you have already posted。示例中到处都有 function
关键字。
只需按照您通过此代码提供的示例进行操作即可:
Schema.pre('save', function (next) {...
你会得到以下内容
你可能想看看 Whosebug 上的这个问题:
- How does the "this" keyword work?