Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Cannot read properties of null (reading 'name') #378

Open
toppirl opened this issue Dec 12, 2023 · 0 comments
Open

TypeError: Cannot read properties of null (reading 'name') #378

toppirl opened this issue Dec 12, 2023 · 0 comments

Comments

@toppirl
Copy link

toppirl commented Dec 12, 2023

My app was working correctly a week ago, or so I thought, but I am now getting the following error when I try and register a new user using User.register()

Really not sure what happened as this error didn't get thrown the first time I created a user, but now it happens every time. The weird thing is, the user still gets saved into the DB and I am able to log in with the newly registered user's credentials.

If I just log the error and don't handle it, the app works, but it seems like I am just putting a temporary fix on it.

This is what gets logged:

error while user register! TypeError: Cannot read properties of null (reading 'name')
node_modules/passport-local-mongoose/index.js:247:30
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

TypeError: Cannot read properties of null (reading 'name')

Here is my auth controller

exports.postSignup = (req, res, next) => {
   User.register(
    new User({ email: req.body.email }),
    req.body.password,
    function (err) {
      if (err) {
      //THIS IS WHERE ERROR IS OCCURING
        console.log('error while user register!', err)
        console.log(err)
        return next(err)
      }
      if (err.name === 'MongoServerError' && err.code === 11000) {
        // Duplicate key error, handle it appropriately
        console.log('User with the same email already exists.')
        req.flash('errors', { msg: 'User with the same email already exists.' })
        return res.redirect('../signup')
      }

      console.log('user registered!')

      res.redirect('/login')
    }
  )
}

Here is my User Schema:

const passportLocalMongoose = require('passport-local-mongoose')
const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  email: { type: String, unique: true, required: true },
  active: { type: Boolean, default: false },
})

UserSchema.plugin(passportLocalMongoose, {
  usernameField: 'email',
  usernameUnique: false,
  findByUsername: function (model, queryParameters) {
    // Add additional query parameter - AND condition - active: true
    queryParameters.active = true
    return model.findOne(queryParameters)
  },
})

module.exports = mongoose.model('User', UserSchema)

Here is my passport config:

const User = require('../models/User')

module.exports = function (passport) {
  passport.use(User.createStrategy())
  passport.serializeUser(User.serializeUser())
  passport.deserializeUser(User.deserializeUser())
}

Here is my server file:

const express = require('express')
const app = express()
const passport = require('passport') // authentication for Login
const session = require('express-session') // so users can stay logged in as they move across application
const flash = require('express-flash') // show us notifications throughout app
const logger = require('morgan') // logs stuff to console for viewing
const connectDB = require('./config/database') // connect to database
const mainRoutes = require('./routes/main') // main routes
const dhrRoutes = require('./routes/dhrecords') // dhr routes
const searchRoutes = require('./routes/search') // search routes
const userRoutes = require('./routes/user') // user routes
const methodOverride = require('method-override')

//Use .env file in config folder
require('dotenv').config({ path: './config/.env' })

// Passport config
require('./config/passport')(passport)

//Connect To Database
connectDB()

//Using EJS for views
app.set('view engine', 'ejs')

//Static Folder
app.use(express.static('public'))

//Body Parsing (must be before routes)
app.use(express.urlencoded({ extended: true }))
app.use(express.json())

// Use the session middleware - stored in MongoDB
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
  })
)

// Passport middleware
app.use(passport.initialize())
app.use(passport.session())

// Custom middleware to set res.locals.isAuthenticated
app.use((req, res, next) => {
  res.locals.isAuthenticated = req.isAuthenticated()
  next()
})

//Use flash messages for errors, info, ect...
app.use(flash())

//Logging
app.use(logger('dev'))

//Use forms for put / delete
app.use(methodOverride('_method'))

//Setup Routes For Which The Server Is Listening
app.use('/', mainRoutes)
app.use('/dhr', dhrRoutes)
app.use('/search', searchRoutes)
app.use('/users', userRoutes)

app.listen(process.env.PORT, () => {
  console.log(`App listening on port ${process.env.PORT}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant