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
}
An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With