Working with databases

Using Async models you can retrieve database data and return the data as a promise. In the example below, we are using rethinkDB:

You need to install the module first:

npm install -S `rethinkdb`

Example rethinkdb data

Setting up the model /models/index.js:

const r = require('rethinkdb'),
    databaseName = 'myDb';

const model = async (request, reply, modelConfig, language, manifest) => {
    let connection, records;
    const databaseConfig = manifest.databases[databaseName];

    try {
        connection = await r.connect(databaseConfig);
        records = await r.table('users').run(connection);
    }
    catch (err) {
        console.warn(err);
        records = [];
    }
    // connection might not exists when an error is thrown during r.connect()
    // check this before you close the connection
    if (connection) {
        connection.close();
    }

    return {
        records
    };
};

module.exports = model;

OFFLINE