Mongoose Schema Plugins

JS
S
JavaScript

Augment Schema functionality using plugins

1// ======================================================
2const plugin = function createdAtPlugin(schema, options) {
3  // Add new property to Schema
4  schema.add({ createdAt: Date });
5  schema.pre('save', function(next) {
6    this.createdAt = new Date();
7    next();
8  });
9  if (options && options.index) {
10    schema.path('createdAt').index(options.index);
11  }
12};
13export default plugin;
14
15
16// models/plugins/plugin.ts
17// ======================================================
18const plugin = function updateOnPlugin (schema, options){
19    // Add new property to Schema
20    schema.add({ updatedOn: Date});
21    // Pre Hook
22    schema.pre('save', function(next) {
23        this.updatedOn = new Date;
24        next();
25    });
26    if(options && options.index){
27        schema.path('updatedOn').index(options.index);
28    }
29}
30export default plugin;
31
32
33// models/item.ts
34const itemSchema = new mongoose.Schema({
35    name: String,
36    description: String,
37    category: String,
38    estvalue: Number
39},options)
40itemSchema.plugin(updatedOnPlugin);
41itemSchema.plugin(plugin2);
42const Item = mongoose.model('Item', itemSchema)
43
44
45// Via community NPM packages
46// npm install mongoose-times --save
47// this will add 'created' and 'updatedAt' fields to the collection docs
48import * as timePlugins from 'mongoose-times';
49itemSchema.plugin(timePlugins, {created: 'createdOn', lastUpdated: 'updatedOn'});

Created on 1/10/2018