How do I fix cast error to object Id failed in mongoose?

567 Views Asked by At

I'm using passport js for google authentication and when I try going to login page I get this error "CastError: Cast to ObjectId failed for value "xxxxxxxx" (type string) at path "_id" for model "User"". How can I fix this?

Here's my schema code *

const {Schema,model} = require("mongoose"); 
const passportLocalMongoose = require("passport-local-mongoose"); 
const userSchema = new Schema({
username: {
    type: String, 
    unique: true, 
}, 
email: {
    type: String, 
    unique:true, 
},
googleid:{
    type: String,
    
} 
}, {timestamps:true})
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });
module.exports = model("User", userSchema);* 

here's my google authentication code

const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth2').Strategy
const User = require('../../database/models/user')
require('dotenv').config()

passport.serializeUser((user, done) => {
  done(null, user)
  console.log(user)
})
passport.deserializeUser((id, done) => {
  console.log('chigala')
  User.findById(id).then(user => {
    done(null, user)
  })
})

const params = {
  clientID: process.env.GOOGLE_OAUTH_CLIENT_ID,
  clientSecret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
  callbackURL: 'http://localhost:5000/api/google/auth',
  passcallbackURL: true
}

const Strategy = new GoogleStrategy(
  params,
  async (req, accessToken, refreshToken, profile, done) => {
    console.log(profile)
    try {
      const currentUser = await User.findOne({ email: profile.emails[0].value })
      if (currentUser) {
        // console.log(`this is the current user:${currentUser}`)
        if (currentUser.googleId) {
          done(null, currentUser)
          return
        }
        currentUser.googleId = profile.id
        currentUser.save()
        done(null, currentUser)
      } else {
        const user = await User.create({
          googleId: profile.id,
          email: profile.emails[0].value
        })
        done(null, user)
      }
    } catch (err) {
      console.log(err)
    }
  }
)
passport.use(Strategy)
1

There are 1 best solutions below

0
On

The default findById method tries to cast id to the MongoDB _id format so this throws an error. In the deserialize function you can use new objectId(id) to cast id to the MongoDB _id format.

const objectId= require('mongodb').ObjectId; //here
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth2').Strategy
const User = require('../../database/models/user')
require('dotenv').config()


passport.deserializeUser((id, done) => {
  console.log('chigala')
  User.findById(new objectId(id)).then(user => {  //here
    done(null, user)
  })
})