Search code examples
javascriptnode.jsexpressmongoosepassport-local

First param to schema.plugin must be a function (passport-local-mongoose)


i have been trying to use passport-local-mongoose in my server. was making this server with the help from a teutorial video. in the teutorial video this same code works perfectly fine, but in my case its not working. Though I have my database connected to mongodbatlas. but I am getting a error "First param to schema.plugin() must be a function," Screenshot of the ERROR

I wonder how would i use plugin as a function! tried searching in everywhere but nothing helpfull. following is the code

const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = ("passport-local-mongoose");

const app = express();
app.use(session({
    secret: "alpha beta gama",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb+srv://admin-sumit:password@cluster0-bessu.mongodb.net/myBlog", {
   useNewUrlParser: true,
   useUnifiedTopology: true
 });

const userSchema = new mongoose.Schema({
    email:String,
    password:String,
    comments:String
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get("/blog1comment", function(req, res){
    if(req.isAuthenticated()){
        res.render('blogsingle', { title: 'Express' });
    } else{
        res.redirect("/login");
    }
});

app.post('/register', function(req, res){
    User.register({username: req.body.username}, req.body.password, function(err, user){
        if(err){
            console.log(err);
            res.redirect("/register");
        } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
            });
        }
    });

});

app.post('/login', function(req, res){
    const user = new User({
        username: req.body.username,
        password: req.body.password
    });
    req.login(user, function(err){
        if(err){
            console.log(err);
        } else{
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
            });
        }
    });
});

app.listen(process.env.PORT || 3000, function(){
    console.log('Server is running');
});

Kindly help me out in this.


Solution

  • const passportLocalMongoose = ("passport-local-mongoose");
    

    Simply I did not used require in there, silly me. Now it is solved.

    const passportLocalMongoose = require("passport-local-mongoose");
    

    This solved it.