Thursday, 11 May 2017

passport-local-mongoose User.register() keep getting error

I am having trouble trying to solve the User.register method (passport-local-mongoose) and keep getting errors after trying to find the bug or missing something that is causing the error.

The error I am keep getting (unchanged) when submit the new register form: [Error: Can't use $or with ObjectId.]

I have looked around for similar issue addressing the error code and doesnt seem to solve it at all. I have had the code(register) set up the same way on my other project and it works just fine.

User Model

//----------------------------------------------------------------------------\\
var mongoose   = require('mongoose');
var localpassport = require('passport-local-mongoose');
//----------------------------------------------------------------------------\\
var userSchema = new mongoose.Schema({
    username: String,
    password: String,
    firstname: String,
    lastname: String,
    subs: [
        {
            id: 
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'Business'
            },
            name: String
        }
    ]
});
//----------------------------------------------------------------------------\\
userSchema.plugin(localpassport);
module.exports = mongoose.model('User', userSchema);

index.js main file to run on nodejs

//REQURES
var express         = require('express'),
    bodyParser      = require('body-parser'),
    mongoose        = require('mongoose'),
    Business        = require('./models/business/businesses'),
    Location        = require('./models/location/locations'),
    Contact         = require('./models/contact/contacts'),
    Comment         = require('./models/comment/comments'),
    Image           = require('./models/media/images'),
    User            = require('./models/user/users'),
    seedBus         = require('./seed/seedBus'),
    seedAll         = require('./seed/seedAll'),
    seedUse         = require('./seed/seedUse'),
    passport        = require('passport'),
    localStrat      = require('passport-local'),
    methodOverride  = require('method-override');
//----------------------------------------------------------------------------\\
//DATABASE SEED
//seedBus();
//seedUse();
//seedAll();
//----------------------------------------------------------------------------\\
//CONNECT TO MONGODB
mongoose.connect('mongodb://localhost/dbc_v1');
//----------------------------------------------------------------------------\\
//VARIABLES
var app = express();
//----------------------------------------------------------------------------\\
//SET and USE
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(methodOverride('_method'));
app.use(bodyParser.urlencoded({extended: true}));
//----------------------------------------------------------------------------\\
//PASSPORT CONFIGURATION
app.use(require('express-session')({
    secret: "May the force be with you",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrat(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//Check if user is logged in or not and flash message
app.use(function(req, res, next) {
    res.locals.currentUser = req.user;
    next();
});
//----------------------------------------------------------------------------\\
//ROUTES
//(index.ejs) Main page
app.get('/', function(req, res) {
    Business.find({})
    .populate('location')
    .exec(function(err, bus) {
        if(err) {
            console.log(err);
        }
        res.render('index', {bus:bus});
    });
});
//----------------------------------------------------------------------------\\
//(BUSINESS GET/POST/PUT/DELETE/SHOW)
//(new.ejs) Business form
app.get('/bus/new', function(req, res) {
    res.render('bus/new');
});
//POST route for NEW
app.post('/bus', function(req, res) {
    Business.create({
        name: req.body.name,
        type: req.body.type,
        logo: req.body.logo,
        desc: req.body.desc,
        video: req.body.video,
        url: req.body.url
    }, function(err, business) {
        if(err) {
            console.log('Business :', err);
        }
        var businessId = business._id;
        console.log(businessId);
        Business.findById({'_id':businessId}, function(err, bus) {
            if(err) {
                console.log(err);
            }
            //Location
            Location.create({
                street: req.body.street,
                city: req.body.city,
                state: req.body.state,
                zipcode: req.body.zipcode
            }, function(err, loc){
                if(err) {
                    console.log('Location : ', err);
                }
                Contact.create({
                    email: req.body.email,
                    phone: req.body.phone,
                    twitter: req.body.twitter,
                    facebook: req.body.facebook,
                    instagram: req.body.instagram
                }, function(err, con) {
                    if(err) {
                        console.log('Contact: ', err);
                    }
                    Image.create({
                        imgA: req.body.imgA,
                        imgB: req.body.imgB,
                        imgC: req.body.imgC,
                        imgD: req.body.imgD,
                        imgE: req.body.imgE
                    }, function(err, img){
                        if(err) {
                            console.log('Image: ', err);
                        }
                        bus.location.push(loc);
                        bus.contact.push(con);
                        bus.images.push(img);
                        bus.save();
                        res.redirect('/');
                    });
                });
            }); 
        }); 
    });
});
//(edit.ejs) Edit Route 
app.get('/bus/:id/edit', function(req, res) {
    Business.findById(req.params.id)
    .populate('location')
    .populate('contact')
    .populate('images')
    .exec(function(err, bus) {
        if(err) {
            console.log(err);
        } else {
            res.render('bus/edit', {bus:bus});
        }
    });
});
app.put('/bus/:id', function(req, res) {
    var location = req.body.location;
    location.forEach(function(loc) {
        Location.findByIdAndUpdate(loc.id, 
        {
            street:loc.street,
            city:loc.city,
            state:loc.state,
            zipcode:loc.zipcode
        }, function(err, loc) {
            if(err) {
                console.log(err);
            }
        });
    });
    var contact = req.body.contact;
    contact.forEach(function(con) {
        Contact.findByIdAndUpdate(con.id, 
        {
            email:con.email,
            phone:con.phone,
            twitter:con.twitter,
            facebook:con.facebook,
            instagram:con.instagram
        }, function(err, con) {
            if(err) {
                console.log(err);
            }
        });
    });
    var images = req.body.images;
    images.forEach(function(img) {
        Image.findByIdAndUpdate(img.id, 
        {
            imgA:img.imgA,
            imgB:img.imgB,
            imgC:img.imgC,
            imgD:img.imgD,
            imgE:img.imgE
        }, function(err, img) {
            if(err) {
                console.log(err);
            }
        })
    })
    Business.findByIdAndUpdate(req.params.id, req.body.bus, function(err, bus) {
        if(err) {
            console.log(err);
        }
        res.redirect('bus/' + req.params.id);
    });
});
//Delete Route
app.delete('/bus/:id', function(req, res) {
    Business.findById(req.params.id, function(err, bus) {
        if(err) {
            console.log(err);
            res.redirect('/');
        }
        console.log(bus);
        Location.findByIdAndRemove(bus.location.toString(), function(err) {
            if(err) {
                console.log(err);
                res.redirect('/');
            }
            Contact.findByIdAndRemove(bus.contact.toString(), function(err) {
                if(err) {
                    console.log(err);
                    res.redirect('/');
                }
                Image.findByIdAndRemove(bus.images.toString(), function(err) {
                    if(err) {
                        console.log(err);
                        res.redirect('/');
                    }
                    Business.findByIdAndRemove(req.params.id, function(err) {
                        if(err) {
                            console.log(err);
                            res.redirect('/');
                        }
                        res.redirect('/');
                    });
                });
            });
        });
    });
});
//(show.ejs) Show business page by id
app.get('/bus/:id', function(req, res) {
    Business.findById(req.params.id)
    .populate('location')
    .populate('contact')
    .populate('comments')
    .populate('images')
    .exec(function(err, bus) {
        if(err) {
            console.log(err);
        }
        res.render('bus/show', {bus:bus});
    });
});
//----------------------------------------------------------------------------\\
//USER (GET, POST, SHOW, UPDATE, DELETE)
//AUTH ROUTES
//(registr.ejs)
app.get('/register', function(req, res) {
    res.render('register');
});
//register logic
app.post('/register', function(req, res) {
    var newUser = new User({username:req.body.username});
    console.log(newUser);
    User.register(newUser , req.body.password, function(err, user) {
        if(err) {
            console.log(err);
            return res.render('register');
        } 
        passport.authenticate('local')(req, res, function() {
            console.log(user);
            res.redirect('/user');
        });
    });
});
//(login.ejs)
app.get('/login', function(req, res) {
    res.render('login');
});
//login logic
app.post('/login', passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login'
    }), function(req, res) {

});
//Login/Logout logic
app.get('/logout', function(req, res) {
    req.logout();
});
//----------------------------------------------------------------------------\\
//MIDDLEWARE

//----------------------------------------------------------------------------\\
//LISTEN
app.listen(process.env.PORT, process.env.IP, function() {
    console.log('Server is running...'); 
});

Register form

<% include partials/header %>

     <div class="container">
            <div class="form-container">
                <form action="/register" method="POST">
                    <!-- business info -->
                    <h3>User information</h3>
                    <input class="form-input" type="text" name="username" placeholder="User Name">
                    <input class="form-input" type="password" name="password" placeholder="Password">
                    <input class="form-input" type="text" name="firstname" placeholder="First Name">
                    <input class="form-input" type="text" name="lastname" placeholder="Last Name">
                    <p><button class="btn btn-xs btn-primary">Submit</button></p>
                </form>
            </div>
        </div>

<% include partials/footer %>

Error Code shows up after submitting the register form

studentDev:~/workspace $ node index.js 
Server is running...
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
{ username: 'Testingworld', _id: 5914d0968c298a0c5c71671b }
[Error: Can't use $or with ObjectId.]



via Matthew Restine

No comments:

Post a Comment