How can I model a relationship between two models created with the toothache hapi plugin?

284 views Asked by At

I'm building a node server using the Hapi framework, and I'm trying to use the toothache plugin to create the CRUD endpoints for MongoDB, but I can't figure out for the life of me how to create a relationship between two objects.

I reduced the app to a very simple scenario:

I have two CRUD schemas, one for authors and one for books. A book contains the id of its author, but not the name. The question is: how can I write a route that returns a book containing also the name of the author?

var bookCRUD = {
    collection: 'books',
    create: {
        payload: Joi.object().keys({
            authorId: Joi.string().required(),
            title: Joi.string().required()
        }),
    },
    update: {
        payload: Joi.object().keys({
            authorId: Joi.string(),
            title: Joi.string()
        }),
    }
}

var authorCRUD = {
    collection: 'authors',
    create: {
        payload: Joi.object().keys({
            name: Joi.string().required()
        }),
    },
    update: {
        payload: Joi.object().keys({
            name: Joi.string().required()
        }),
    }
}

We apply toothache on both schemas, and obtain two models:

var Book = require('toothache')(bookCRUD);
var Author = require('toothache')(authorCRUD);

A route to retrieve a certain book would look like that:

plugin.route({
    path: '/books/{id}',
    method: 'GET',
    config: {
        handler: Book.get
    }
});

and would return:

{
    "_id": "54762fd0654c479400daa9d4",
    "authorId": "547607c7c80064281e7a7b50",
    "title": "Some Book Title"
}

How could I interrogate the Author model in the same handler, to obtain an answer like:

{
    "_id": "54762fd0654c479400daa9d4",
    "authorId": "547607c7c80064281e7a7b50",
    "authorName": "Some Great Writer",
    "title": "Some Book Title"
}

It seems like the toothache plugin makes very difficult to model relational data, and that's a shame, because in the real world, you won't be able to have only embedded arrays, and will be forced to use normalised data. I would really appreciate some help with that. Thank you in advance!

0

There are 0 answers