Search code examples
node.jsmongoosepassport.jspassport-local

Nodejs : passport-local-mongoose's .plugin(...) doesn't do anything


I'm trying to use passport-local-mongoose in order to register users in my MongoDB database. However it seems like it's not doing what it is supposed to.

Model:

var userSchema = new mongoose.Schema({
    email: {
        type: String,
        ...
    },
});

userSchema.plugin(passportLocalMongoose, {usernameField: 'email'});

userSchema.statics = {
    ...
}

userSchema.methods = {
    ...
}

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

Controller:

exports.registerAction = async (req, res, next) => {
    const user = new User({ email: req.body.email });
    User.register(user, req.body.password, function() {
        res.send('It works!');
    });

As I understand it, Passport is supposed to implement the register method on User, but here User.register stays undefined.

What am I doing wrong?


Solution

  • I found the solution by myself.

    The userSchema.plugin(...) call has to be made after defininguserSchema.statics = {…} and userSchema.methods = {…}.

    I guess .plugin(...) tries to use the statics or methods property (or both), and initializes them as an new object. Then, when we call userSchema.statics = {…} (or methods), it simply erases what .plugin(...) had created.