Models and documents

A model contains the schema for your data. Models correspond to a table/collection in a database.

Creating a new model

New models should be created in the app/models folder.

You can inherit from the Alchemy.Model class directly, but since the alchemy-skeleton always comes with a base App model that is preferred.

This is how you inherit from the App model.

The name of the new class is taken from the function name.


/**
 * Page model
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.0
 * @version  0.1.0
 * 
 * @param    {Object}   options
 */
var PageModel = Function.inherits('Alchemy.Model.App', function Page(options) {
	Page.super.call(this, options);
});

This call to Function.inherits will return the same Page function we can use to add fields & methods to.

If you want to access the class outside of this file, it is also available in Classes.Alchemy.Model.Page

Adding fields to the model schema

We add fields to a model in a constitute function. Functions added like this will also run on child classes.

A new model will always contain an _id, created and updated field by default.


/**
 * Constitute the class wide schema
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.1.0
 * @version  0.1.0
 */
PageModel.constitute(function addFields() {
	
	// Let's give the page a name
	this.addField('title', 'String');
	
	// And also a body, which should be HTML
	this.addField('body', 'Html');
	
	// We can also define associations like this:
	// (In this case, a `user_id` field will be added to this model's schema)
	this.belongsTo('User');
});

Creating new documents

Let's create a new document and save it to the database. Let's get an instance of this model first:

In this example we use Model.get('Page') because the code is not running in any instance context, but normally you should use this.getModel('Page')


// Create a new instance of the Page model
// When this code is in an action or any class method,
// you should use `this.getModel('Page')` instead!
var page_model = Model.get('Page');

Now that we have a model instance we can create a document and begin setting the content


var page = page_model.createDocument();
page.title = 'This is my title';
page.body = '<p>This is some html</p>'

Just use the save() method to store it in the database. It returns a promise:


await page.save();

Finding documents

Now that we have stored a single document, we can go look for it. In order to find a single document you can do this:


var page = await page_model.find('first');

We can also use a criteria when we want to add some conditions:


// A `find()` with no arguments returns a criteria
var criteria = page_model.find();

criteria.where('title').contains('is my');

// And then find it
page = await page_model.find('first', criteria);