Object does not exist - Mongodb

147 Views Asked by At

Error: I'm having an error of "Cannot set property 'username' of null." It seems like the error happens when I try to find the currently logged in user with "User.findOne"

Question: Why would req.user be found but then the code not be able to find the currently logged in user? What should I change to make sure it does find the logged in user which I know exists.

To access this route a user must be logged in:

   router.post("/updateAccount", function(req, res){
    
    if (req.user) {
    
    User.findOne({username: req.body.currentUser}, function(err, user) {
    if (err) {
    return done(err);
    }
    
    user.username = req.body.username;

    ...});
2

There are 2 best solutions below

0
Shujja On BEST ANSWER

Try async await

router.post("/updateAccount", async function(req, res){

if (req.user) {

await User.findOne({username: req.body.currentUser}, function(err, user) {
if (err) {
return done(err);
}

user.username = req.body.username;

...});
1
Shujja On

I think you're not using BodyParser in you main server