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.
constblogPostSchema=newSchema({ title: {} });// Custom method to retrieve all children Text entitiesblogPostSchema.methods.texts=functiongetTexts() {// the scope (this) is the entity instanceconstquery=this.model('Text').query().hasAncestor(this.entityKey);returnquery.run();};// In your Controller// You can then call it on an entity instance of BlogPostconstBlogPost=require('../models/blogpost.model');BlogPost.get(123).then((blogEntity) => {blogEntity.texts().then((response) => {consttexts= 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:
// Add custom "profilePict()" method on the User SchemauserSchema.methods.profilePicture=functionprofilePicture() {// Any type of query can be done herereturnthis.model('Image').get(this.imageIdx);};// In your controllerconstUser=require('../models/user.model');constuser=newUser({ name:'John', imageIdx:1234 });user.profilePicture().then((imageEntity) => {user.profilePicture =imageEntity.url;user.save().then(() { ... }); });// Or with a callbackuserSchema.methods.profilePict=function(cb) {returnthis.model('Image').get(this.imageIdx, cb);};...constuser=newUser({ name:'John', imageIdx:1234 });// Call custom Method 'getImage'user.profilePict(functiononProfilePict(err, imageEntity) {user.profilePict =imageEntity.url;user.save().then(() { ... });});