Mongoose Document (ix) Plugins

Source: Internet
Author: User

Plug - ins

Schemas are pluggable, that is, they can apply pre-packaged capabilities to extend their functionality. This is a very powerful feature.

Suppose we have several collection in our database, to add the last-modified functionality to them. It's easy to use plugins. Just create a plug-in and apply it to each schema:

//Lastmod.jsModule.exports = exports =functionlastmodifiedplugin (schema, options) {Schema.add ({lastmod:date}) Schema.pre (' Save ',function(next) { This. Lastmod =NewDate Next ()}) if(Options &&options.index) {Schema.path (' Lastmod '). Index (Options.index)}}//Game-schema.jsvarLastmod = require ('./lastmod '));varGame =NewSchema ({...}); Game.plugin (Lastmod, {index:true });//Player-schema.jsvarLastmod = require ('./lastmod '));varPlayer =NewSchema ({...}); Player.plugin (lastmod);

We just added the last-modified feature to the game and player schema and declared an index to the game's lastmod path to boot.

Global plugins

Want to register a plugin for all shcema? The function of Mongoose Singleton mode plugin() can register a plugin for all schemas. For example:

var mongoose = require (' Mongoose '); Mongoose.plugin (Require ('./lastmod ')); var New Schema ({...}); var New Schema ({...}); // ' Lastmodifiedplugin ' gets attached to both schemas var Game = Mongoose.model (' Game ', Gameschema); var Player = Mongoose.model (' Player ', playerschema);

Mongoose Document (ix) Plugins

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.