1

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.

AlexZeDim
  • 1,624
  • 1
  • 12
  • 31
  • If my answer was helpful or provide a suggested information, please up vote it, (or down-vote, if it doesn't) and close the question, by accepting an answer. Thank you. – AlexZeDim Jul 25 '20 at 09:31

1 Answers1

1

It's nothing wrong with mongo or mongoose, it's arrow function declaration.

Check the link that you have already posted. There is function keyword everywhere in examples.

Just follow the examples that you have provided via this code:

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

and you will get the following

You might wanna take a look at this questions on StackOverflow:

Also, MDN this MDN link about arrow functions.

AlexZeDim
  • 1,624
  • 1
  • 12
  • 31