Custom methods
Custom methods can be added to entities instances through their Schemas.
schema.methods.<methodName> = function(){ ... }
Make sure not to use arrow function as you would lose the scope of the entity instance.
const blogPostSchema = new Schema({ title: {} });
// Custom method to retrieve all children Text entities
blogPostSchema.methods.texts = function getTexts() {
// the scope (this) is the entity instance
const query = this.model('Text')
.query()
.hasAncestor(this.entityKey);
return query.run();
};
// In your Controller
// You can then call it on an entity instance of BlogPost
const BlogPost = require('../models/blogpost.model');
BlogPost.get(123)
.then((blogEntity) => {
blogEntity.texts()
.then((response) => {
const texts = response[0].entities;
});
});Note how entities instances can access other models through entity.model('MyModel'). Denormalization can then easily be done with a custom method:
Last updated
Was this helpful?