Noah
Noah

Reputation: 4761

Mongoose schema method is "not a function"

My model looks like this, but when I try use verifyPassword, it says TypeError: user.verifyPassword is not a function

const User = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  avatar: String,
  token: String,
  role: String,
  permissions: Array,
  email: {
    type: String,
    unique: true,
    required: true
  },
  joined: {
    type: Number,
    default: ( new Date() * 1 )
  }
})

User.methods.verifyPassword = function (password) {
  return bcrypt.compare(password, this.password)
}

I use it like this.

yield User.find({
  email: this.request.body.email
}).exec()
.then( user => {
  if ( user.verifyPassword(self.request.body.password) ) {
    self.status = 200
    self.body = {
      token: user.token
    }
  } else {
    self.status = 500
    self.body = "Problem signing in."
  }
}, error => {
  self.status = 500
  self.body = "Problem signing in."
})

Upvotes: 1

Views: 5400

Answers (1)

Florian
Florian

Reputation: 712

Mongo's "find" returns an iterable cursor of results (potentially there are none). If you expect to get one result only, try "findOne" instead. This will return one document.

Upvotes: 12

Related Questions