Search code examples
node.jsmongodbexpresserror-handlingmlab

Object does not exist - Mongodb


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;

    ...});

Solution

  • 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;
    
    ...});