What We Will Cover
Plug-ins
Middleware
Hooks
Discriminators
Promises
Main Take-away
– MongoDB is “schema-less”
– Everything in Mongoose starts with a Schema
Schema
– Defines the model “shape”
// Standup Model
var mongoose = require( 'mongoose' );
var Schema = mongoose.Schema;
var standupSchema = new Schema({
memberName: {
type: String,
required: true,
default: 'Mark'
},
// abbreviated for brevity...
});
// child address schema...
var addressSchema = new Schema({
type: String,
street: String,
city: String,
state: String,
country: String,
postalCode: Number
});
// parent customer schema...
var customerSchema = new Schema({
name: {
first: String,
last: String
},
address: [ addressSchema ],
createdOn: { type: Date, default: Date.now },
isActive: { type: Boolean, default: true }
});
// Start with the Schema
var personSchema = new Schema({
firstName: String,
lastName: String
});
// Build a model from the customer schema...
var Person = mongoose.model(‘Person’, personSchema);
// Create a document from the model
var bob = new Person({
firstName: ‘Bob’,
lastName: ‘Doe’
});
var query = { name: ‘old name’ };
var updates = { name: ‘new name’ };
var options = { new: false };
Person.findOneAndUpdate(query, updates, options, callback)
findOneAndUpdate – Mongoose Version 3.x
To return the original document rather than the updated document… set the option
“new” to false.
Defaults to true.
#“new: bool – if true, return the modified document rather than the original. defaults to false (changed in 4.0)”
Mongoose Validation :
var schema = new Schema({
itemName: {
type: String,
required: true
}
});
Query
– .then(…)
Mongoose 3
– To get promise… first call .exec()
– Person.find({ }).exec().then(…);
Mongoose 4
– Queries returned by .find() are promises
– Person.find({}).then(…);
Semantic versioning :
Given a version number MAJOR.MINOR.PATCH, increment the:
MAJOR – version when you make incompatible API changes,
.MINOR – version when you add functionality in a backwards-compatible manner, and
.PATCH – version when you make backwards-compatible bug fixes.
Schema Improvement – Options :
var mongoose = require('mongoose')
var pizzaSchema = new mongoose.schema(
{
size:string,....
},
{ strict: false }
) //false: allow to save
var pizza = mongoose.model('Pizza', pizzaSchema)
var takenAndBakePizza = new Pizza({isTakenAndBake: true})
takenAndBakePizza.save()
var Pizza = mongoose.model('Pizza', pizzaSchema)
Pizza.findOneAndUpdate({_id: ___},{isTakeAndBake: false}, function(error) {...})
//Validation array of Objects
var pizzaSchema = new mongoose.Schema({
validate: {
validator: function(val) { return val.length > 1}
}
})
Middleware 4 –
1.Query Middleware – Methods [count, find, findOne, findOneAndUpdate, findOneAndRemove, insertMany, update]
2.Document Middleware – Methods [init, validate, save, remove]
https://github.com/Automattic/mongoose/wiki
https://mongoosejs.com/docs/guide.html#safe (v5.10.3)
Extending Functionality with Plugins
1.Custom Plug-in : Building your own plug-in Applying it to the Schema
2.Mongoose Plug-in Library : npm repository Plug-ins shared by other developers
1.Custom Plug-in :
a.Item Model “item.model.js”
var mongoose = require('mongoose');
var updatedOn = require('../plugins/updatedOn');
var valueIndicator = require('../plugins/valueIndicator');
var itemSchema = mongoose.Schema({
name: String,
description: String,
category: String,
estvalue: Number
},
{ strict: false }
);
itemSchema.plugin(updatedOn);
itemSchema.plugin(valueIndicator);
var Item = mongoose.model('Item', itemSchema);
// Custom validator
Item.schema.path('estvalue').validate(function (value) {
return value > 0;
}, 'Estimated value must be greater than 0!');
module.exports = Item;
b.”valueIndicator.js”
var plugin = function valueIndicatorPlugin (schema) {
schema.post('find', function (result) {
result.forEach(function(element) {
if (element.estvalue >= 100)
element.description += ' ($)';
}, this);
});
}
module.exports = plugin;
c. “updateOn.js”
var plugin = function updatedOnPlugin (schema, options) {
schema.add({ updatedOn: Date })
schema.pre('save', function (next) {
this.updatedOn = new Date;
next();
})
if (options && options.index) {
schema.path('updatedOn').index(options.index)
}
}
module.exports = plugin;
“pre” Hook Plug-in : Save()
“post” Hook Plug-in : find()/findOne()
https://mongoosejs.com/docs/4.x/docs/validation.html