Skip to content

Instantly share code, notes, and snippets.

@c0d0g3n
Created May 3, 2017 16:28
Show Gist options
  • Save c0d0g3n/c7f382bb858ac2fa797f4edd4097b40b to your computer and use it in GitHub Desktop.
Save c0d0g3n/c7f382bb858ac2fa797f4edd4097b40b to your computer and use it in GitHub Desktop.
Explaining how Mongoose setters work
// dependencies
let mongoose = require('mongoose')
let Promise = require('bluebird')
mongoose.Promise = Promise
// connect to local db help
mongoose.connect("mongodb://localhost/help")
let db = mongoose.connection
db.on('error', (err) => {
return console.error('Connection error:', err)
})
// define mongoose schema
let fruitSchema = new mongoose.Schema({
kind: {
type: String,
// below function is called every time a new value to this property is assigned
set: function (input) {
if (this.kind) {
// this.kind is defined, don't change it
console.warn('You cannot override the value of apple.kind.')
return this.kind
} else {
// this.kind was not defined yet, use the input as value
return input
}
}
}
})
// create Fruit model
let Fruit = mongoose.model('Fruit', fruitSchema)
console.log("creating doc...")
let apple = new Fruit({
// initialization: doc will take this value because right now kind is undefined
kind: "apple"
})
apple.save()
.then((apple) => {
// try to override apple, doesn't work, warning thrown
console.log("trying to override...")
apple.kind = "strawberry"
return apple.save()
})
.then((apple) => {
console.log("Final value: " + apple.kind)
})
.catch((error) => {
console.error(error)
})
// NOTE: a property's set function appears to be called every time that property gets assigned a new value,
// not upon saving the doc like I claimed before.
{
"name": "help",
"version": "1.0.0",
"description": "",
"main": "help.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.5.0",
"mongoose": "^4.9.7"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment