Schema Definition
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
}
DataBase
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);
})
})
In the Schema definition file, when I am logging out this.name
and it is giving undefined
I could not understand this behavior, I have gone through this site and followed it but still couldn't find the way to recognize the error.