Home > Software engineering >  user.setPassword is not a function
user.setPassword is not a function

Time:06-21

I'm trying to change the user's password with the setPassword() passport local mongoose instance method, but I'm getting an error that says "user.setPassword is not a function". This is my code

const change_password = (req, res) => {
    const password = req.body.password
    console.log(password);
    User.find({
        _id: req.user._id
    }).then((user) => {
        user.setPassword(password, function() {
            console.log('user password changed')
            user.save()
            res.status(200).json( { msg : 'The password has been changed' })
        })
    }).catch(e => {
        console.log(e);
    })
}

And this is my user Schema

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

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        //  required: true
    },
    googleId: {
        type: String,
    },
    photoUrl: {
        type: String,
    },
    githubId: {
        type: String,
    },
    twitterId: {
        type: String,
    },
    facebookId: {
        type: String,
    },
    bio: {
        type: String,
    },
    email: {
        type: String,
    },
    phoneNumber: {
        type: String,
    },
})

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

const User = mongoose.model('User', UserSchema);

module.exports = User;

CodePudding user response:

User.find() will return an array of users matching the query, hence the error.

Because there should be (at most) one user in the database matching req.user._id, use findOne instead. Also note that findOne() can return null in case there were no users matching the query:

User.findOne({ _id: req.user._id }).then(user => {
  if (! user) return res.sendStatus(404);
  user.setPassword(…);
});
  • Related