Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose instance method `this` does not refer to model

EDIT: I have discovered that console.log(this) ran inside the setPassword method returns only the hash and salt. I'm not sure why this is happening, however it indicates that this is not refering to the model as it should.


I have the following schema with the following instance method:

let userSchema = new mongoose.Schema({
  username: {type: String, required: true},
  email: {type: String, required: true, index: {unique: true}},
  joinDate: {type: Date, default: Date.now},
  clips: [clipSchema],
  hash: {type: String},
  salt: {type: String}
})

userSchema.methods.setPassword = (password) => {
  this.salt = crypto.randomBytes(32).toString('hex')
  this.hash = crypto.pbkdf2Sync(password, this.salt, 100000, 512, 'sha512').toString('hex')
}

The instance method is called here, then the user is saved:

let user = new User()

user.username = req.body.username
user.email = req.body.email
user.setPassword(req.body.password)

user.save((err) => {
  if (err) {
    sendJsonResponse(res, 404, err)
  } else {
    let token = user.generateJwt()
    sendJsonResponse(res, 200, { 'token': token })
  }
})

However, when I view the users collection in the mongo CLI, there is no mention of hash or salt.

{
 "_id" : ObjectId("576338b363bb7df7024c044b"),
 "email" : "[email protected]",
 "username" : "Bob",
 "clips" : [ ],
 "joinDate" : ISODate("2016-06-16T23:39:31.825Z"),
 "__v" : 0 
}
like image 637
Moo Avatar asked Jun 16 '16 23:06

Moo


People also ask

What is an instance of a model in Mongoose?

An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.

What does model find return in Mongoose?

The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

Does Mongoose model create collection?

Mongoose by default does not create any collection for the model in the database until any documents are created. The createCollection() method is used to create a collection explicitly.


1 Answers

The reason it was not working was because I was using an arrow method. I had to make it a normal function:

userSchema.methods.setPassword = function (password) {

The reason is because arrow functions treat this differently from regular functions. Please see the following for more detail:

http://exploringjs.com/es6/ch_arrow-functions.html

like image 50
Moo Avatar answered Nov 14 '22 23:11

Moo