Skip to the content.

Using Mongoose as the ORM

Please see here if you haven’t setup the orm-model-config file.

Setting up Models

After configuring your Collection’s Schema(as you do normally for Mongoose) like below:

import mongoose from 'mongoose';
import { Model } from 'pwoli';
...
const eventSchema = new mongoose.Schema(
    {
        title: { type: String, required: true },
        contactPerson: {
            name: { type: String, required: true },
            email: { type: String, required: true, validate: [function(email) {
                var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
                return re.test(email)
            }, 'Please fill a valid email address'] },
            phone: { type: Number, required: true },
        },
        companies: [{
            title: { type: String, required: true },
        }],
        organization: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Organization'
        }
    },
    { collection: 'Event', timestamps: true }
);

Create a Model class for the Schema and override/add required methods(if any) to it as below:

class Event extends (Model) {
    getAttributeLabels() { // used for setting labels for different attributes/paths
        return {
            title: 'Title',
            'contactPerson.name': 'Contact Person\'s Name',
            'contactPerson.phone': 'Contact Person\'s Phone Number',
            'contactPerson.email': 'Contact Person\'s Email',
            organization: 'Organization'
        }
    }
    get sampleGetter() {
        return (async () => {
            return this.title.toUpperCase();
        })();
    }
    get companiesCommaSeparated() {
        let companies = [];
        for(let company of companies)
            companies.push(company.title);
        return companies.join(", ");
    }
    ...
}

Finally, load the class to the created Schema, modelize it, and export it as below:

eventSchema.loadClass(Event);
// since MongoDB doesn't have 'id' by default, we explicitely copy _id to id
eventSchema.set('toJSON', {
  virtuals: true,
  transform: function (_doc, ret, _options) {
      ret.id = ret._id;
  }
});
const EventModel = mongoose.model('Event', eventSchema)
export { EventModel as Event };

Now you can use these Models just as how you use it in the normal way for Pwoli.

Fully working examples of using Mongoose with Pwoli are available here and here.

Operations with Embedded Documents

In Widgets like GridView, ListView, ActiveForm etc., embedded attributes can be used like below:

RESTful APIs:

APIs will work as normal as demonstrated here.

Fully working examples of using Mongoose with Pwoli are available here and here.