Ad

Passport Logout() Error: Cast To ObjectId Failed For Value "logout" At Path "_id" For Model "somemodel(not The User Model)"

I'm a hobbyist coder, and I can usually solve errors with lots of searches, but this one I can't get it right.

when I hit my logout route it throws an error: Cast to ObjectId failed for value "logout" at path "_id" for model "Spot"

I tried mongoose version 4.7.2, it's not working. I can't imagine why is it associating my logout route with the spot model at all.

my app.js

    var express             = require("express"),
    bodyParser          = require("body-parser"),
    mongoose            = require("mongoose"),
    passport            = require("passport"),
    passportFacebook    = require("passport-facebook").Strategy,
    User                = require("./models/user.js"),
    Spot                = require("./models/spot.js");

mongoose.connect("mongodb://localhost/biketrialspots", { useNewUrlParser: true });

var app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));
app.use(require("express-session")({
    secret: "some secret",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

app.use(function(req, res, next){
   res.locals.currentUser = req.user;
   next();
});

passport.use(new passportFacebook({
    clientID: "some id",
    clientSecret: "some secret",
    callbackURL: "somewebsite/auth/facebook/callback",
    profileFields: ['id', 'displayName', 'picture.type(large)']
}, function(accessToken, refreshToken, profile, done) {

        User.findOrCreate(profile, function(err, user) {

             if (err) 
                { return done(err); }

            done(null, user);

        });
    }
));

passport.serializeUser(function(user, done) {
    done(null, user._id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

app.get("/", function(req, res){
    Spot.find({}, function(err, spots){
        if(err){
            console.log(err);
        } else{
            res.render("index", {spots:spots});
        }
    });
});

app.get("/new", ensureAuthenticated, function(req, res){
    res.render("new");
});

app.post("/", function(req, res){
    Spot.create(req.body.spot, function(err, result){
        if(err){
            console.log(err);
        } else{
            res.redirect("/");
        }
    });
});

app.get("/:id", function(req, res){
    Spot.findById(req.params.id, function(err, spot){
        if(err){
            console.log(err);
        } else{
            res.render("spot", {spot: spot});
        }
    });
});

// Redirect the user to Facebook for authentication.  When complete,
// Facebook will redirect the user back to the application at
//     /auth/facebook/callback
app.get('/auth/facebook', passport.authenticate('facebook'));

// Facebook will redirect the user to this URL after approval.  Finish the
// authentication process by attempting to obtain an access token.  If
// access was granted, the user will be logged in.  Otherwise,
// authentication has failed.
app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { successRedirect: '/',
                                      failureRedirect: '/login' }));

app.get("/logout", function(req, res){

    req.user.logout();
        res.redirect('/'); 


});

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    return res.redirect('/');
}

app.listen(process.env.PORT, process.env.IP, function(req, res){
    console.log("APP HAS STARTED!!!!!");
});

user model

var mongoose = require("mongoose");

var userSchema = new mongoose.Schema({
    facebookID:Number,
    username:String,
    photo:String
});

userSchema.statics.findOrCreate = function findOrCreate(profile, cb){
    var userObj = new this();
    this.findOne({facebookID : profile.id},function(err,result){ 
        if(!result){
            userObj.facebookID = profile.id;
            userObj.username = profile.displayName;
            userObj.photo = profile.photos[0].value;
            userObj.save(cb);
        } else{
            cb(err,result);
        }
    });
};

module.exports = mongoose.model("User", userSchema);

Thank you

Ad

Answer

Because app.get("/:id", ...) is written before app.get("/logout", ...) in your code, I guess the request handler of /:id would be called when you get /logout. Then, req.params.id becomes "logout" and the error is thrown by Spot.findById().

How about trying to write app.get("/logout", ...) before app.get("/:id", ...)?

Ad
source: stackoverflow.com
Ad