I am having a problem while making a controller in which there us a userController class which has login and createuser methods and I am trying to access the method I described from the this object but I cannot access the this.userExists() method. When I try to access, it shows that the userExists is undefined.
import User from '../models/User';
class userController {
userExists(username) {
User.findOne({ username }, (err, user) => {
if (!!user) {
return true;
} else {
return false;
}
});
}
login(req, res) {
const data = req.body;
const { username } = data;
console.log(this);
if (!this.userExists(username)) { //returns undefined
res.status(404).json({ success: false, error: 'User not found' });
return;
}
User.findOne(data, ('name', 'username'), (err, user) => {
console.log(user);
if (err) {
res.status(400).json({ success: false, error: 'Error in sever' });
} else {
if (user) {
res.status(200).json({ success: true, user, token: user.generateToken() });
} else {
res.status(404).json({ success: false, error: 'user not found' });
}
}
});
}
create(req, res) {
const data = req.body;
if (this.userExists) {
res.status(403).json({ success: false, error: 'User already exists' });
return;
}
console.log(data);
const user = new User(data);
user.save((err, data) => {
if (err) {
console.log(err);
res.status(400).json({ success: false, error: 'Error in server' });
} else {
res.status(200).json({ success: true, user });
}
});
}
}
export default new userController();