# 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.

```javascript
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:

```javascript
// Add custom "profilePict()" method on the User Schema
userSchema.methods.profilePicture = function profilePicture() {
    // Any type of query can be done here
    return this.model('Image').get(this.imageIdx);
};

// In your controller
const User = require('../models/user.model');

const user = new User({ name: 'John', imageIdx: 1234 });
user.profilePicture()
    .then((imageEntity) => {
        user.profilePicture = imageEntity.url;
        user.save()
            .then(() { ... });
    });

// Or with a callback
userSchema.methods.profilePict = function(cb) {
    return this.model('Image').get(this.imageIdx, cb);
};
...

const user = new User({ name:'John', imageIdx:1234 });

// Call custom Method 'getImage'
user.profilePict(function onProfilePict(err, imageEntity) {
    user.profilePict = imageEntity.url;
    user.save().then(() { ... });
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sebloix.gitbook.io/gstore-node/schema/custom-methods.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
