Reputation: 39
I made this route to check if there is some data in the mongoose or not, and based on this I'm setting state variable to true, and checking at route level if its true and sending response appropriately, I'm getting error response and server crashed with
can not read property of 'state' null
here is the code:
app.get('/authenticate', function(req, res){
var state = false;
user.remove({}, function(err){
if(err){
console.log('didnt clear');
return;
}else{
user.find({}, function(err, data){
if(err){
console.log('error occured while finding');
return;
}
this.state = true;
console.log(this.state);
})
return this.state;
}
})
if(state){
res.json('removed all documents in collection);
}else{
res.json('something bad happened');
}
})
Upvotes: 0
Views: 1809
Reputation: 111278
First of all change:
this.state = true;
console.log(this.state);
to:
state = true;
console.log(state);
Second, this has no effect:
return this.state;
It doesn't matter what you return from the callback, it will be ignored anyway.
Next, this will always be false:
if(state){ ... }
Because this line will get called before any of your callbacks is even started. You are testing the variable before it ever got a chance to be different than the original false
that you assigned to it.
Those are the first problems with that code that come to mind. There may be more problems but first you need to understand the order of evaluation of your statements before you can go into details.
When you test a variable before it could possible be changed then don't expect it to be anything different than the original value that you assigned to it.
Upvotes: 1