Skip to content

Plugin Use Mongoose

MaelVB edited this page Jul 30, 2021 · 1 revision

Plugin Creation

Use Mongoose

In your plugin, you may want to save more informations !

To do that, you can for example :

  • Extend a Database Schema
  • Create a new collection

Extend a database schema

First you need to access to the schema, to do that place a AquilaEvent listenner in your init.js file (init.js is called before the schemas)

Here is an example :

const aquilaEvents =  require('../../utils/aquilaEvents');

module.exports = function () {
    aquilaEvents.on('userSchemaInit', (userSchema) => {
        userSchema.add({
            myNewAttribute        : {type: Boolean, default: null},
            myNewAttributeNumber2 : {type: String, default: null}
        });
    });
};

Legend :

  • You can see here we wanted to extend the userSchema, so we listenned to the userSchemaInit
  • You can find the corresponding name of your event in /orms/schemas/*

How to you use your modification

There are several methods to use new attributes in the schema, one method is simply to listen to an Event to change the attribute

Example in initAfter.js :

const aquilaEvents         = require('../../utils/aquilaEvents');
module.exports = async function (resolve, reject, server, app, passport) {
    try {
        aquilaEvents.on('aqNewUser', async (document) => {
            // change your document here

            // don't forget to save it !
        });
        resolve();
    } catch (err) {
        console.error(`${info.name} -> initAfter.js :`, err);
        reject(err);
    }
};

Legend :

  • Here we are listenning to aqNewUser, to change our attribute when a user is created

Using Collection

You can also created entire collections for your data, to do that, juste create a file in your plugin in /models/YOUR_MODEL.js

In that file, you can put your new schema and his methods, his mongo hooks, etc...

Example :

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const MyNewSchema = new Schema({
    name        : {type: String},
    code        : {type: String, required: true},
});

MultiShopSchema.pre('save', async function (next) {
    // a mongo hook here !
    next();
});

module.exports = mongoose.model('NAME_OF_YOUR_SCHEMA', MyNewSchema, 'NAME_OF_YOUR_SCHEMA');

Legend :

  • It's exactly like a regular schema in /orm/schemas !

How to use your collection

It's exaclty like a normal schema !

Example in a service :

const MyModel = require('../models/YOUR_MODEL'); // we require the schema (as a model)

const getAll = async () => {
    return MyModel.find({});
}

module.exports = {
    getAll
};
Clone this wiki locally