尝试通过护照库使用我的本地策略时,我一直收到此错误。

TypeError: UserModel.findOne is not a function


我环顾了几个小时,但似乎找不到适合我问题的解决方案。这是我的user.model和auth.services文件。

用户模型

const mongoose = require('mongoose');
const validator = require('validator');
const uniqueValidator = require('mongoose-unique-validator');
const jwt = require('jsonwebtoken');

const cryptor = require('../services/bcrypt.services');
const authServices = require('../services/auth.services');

const Schema = mongoose.Schema;

const UserSchema = new Schema({

    email: {
        type: String,
        unique: true,
        trim: true,
        lowercase: true,
        required: [true, 'Email is required'],
        validate: {
            validator: function(email) {
                return validator.isEmail(email);
            },
            message: function (props) { `${props.value} is not an valid email` }
        }
    },
    password: {
        type: String,
        trim: true,
        minlength: [6, 'Password too short'],
        lowercase: true,
        required: true
    },

    conversations: [{ type: Schema.Types.ObjectID, ref: 'Conversation' }]
});

UserSchema.methods = {

    async _hashPassword(password) {
        this.password = await cryptor.hashAsync(password);
    },

    async authUser(password) {
        return await cryptor.compareAsync(password, this.password);
    },

    createToken() {
        return jwt.sign({
            _id: this._id
        }, authServices.privateKey);
    },

    toAuthJWT() {
        return {
            _id: this._id,
            email: this.email,
            token: this.createToken()
        };
    },

    toJSON() {
        return {
            _id: this._id,
            email: this.email
        }
    }

};

UserSchema.pre('save', async function (next) {
    if (this.isModified('password')) {
        this._hashPassword(this.password);
    }

    next();
});

UserSchema.plugin(uniqueValidator, { message: '{VALUE} already exists' });

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


认证服务

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const JWTStrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const UserModel = require('../user/user.model');
const fs = require('fs');



// LocalStrategy
let localStrategy = new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, function(email, password, done) {

    UserModel.findOne({ email: email }, function(err, user) {
        if (err) {
            return done(err);
        } else if(!user) {
            // Invalid email
            return done(null, false);
        } else if(!user.authUser(password)) {
            // Invalid password
            return done(null, false);
        }

        return done(null, user);
    });
});

passport.use(localStrategy);


// JWTStrategy
// eslint-disable-next-line no-undef
const privateKEY = fs.readFileSync(__dirname + '/private.key', 'utf8');
// eslint-disable-next-line no-undef
const publicKEY = fs.readFileSync(__dirname + '/public.key', 'utf8');

let jwtStrategy = new JWTStrategy({
    jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
    secretOrKey: publicKEY
}, function(payload, done) {

    UserModel.findById(payload._id, function(err, user) {
        if (err) {
            return done(err);
        } else if(!user) {
            return done(null, false);
        }

        return done(null, user);
    });

});

passport.use(jwtStrategy);

module.exports = {
    authLocal: passport.authenticate('local', { session: false }),
    authJwt: passport.authenticate('jwt', { session: false }),
    privateKey: privateKEY
};


我看不到为什么找不到UserModel.findOne函数,或者我可能丢失了一些东西。

最佳答案

在您的模式中,您没有扩展现有的方法,而是完全覆盖了它们,即

UserSchema.methods = { ... }


这行代码为methods分配了一个新对象,该对象完全清除了Mongoose提供的所有现有功能(例如findOne)。如果要将静态函数添加到架构,则可以扩展statics

UserSchema.statics.myFunction = () => { ... }

07-24 09:44
查看更多