Search code examples
javascriptnode.jsexpressrethinkdbthinky

Using Think ORM in various files without reconnecting to database


I have a ton of models for thinky and I'm having to create an object in each file for thinky and its connecting like 10 times because I have that many models.

var dbconfig = require('../config/config.js')['rethinkdb'];
var thinky = require('thinky')(dbconfig);
var User = require('./user.js');
var type = thinky.type;
var r = thinky.r;

var Feedback = thinky.createModel("Feedback", {
    id: type.string(),
    feel: type.number().required(), // 0 = sad, 1 = happy
    reason: type.string(),
    description: type.string(),
    createdAt: type.date().default(r.now()),
    createdBy: type.string().required()
});

Feedback.ensureIndex("id");

module.exports = Feedback;

How can I make it so that I don't have to keep instantiating the variable and therefore creating new connections every time and still be able to make all these data models in their own separate file?


Solution

  • I got you homie, here is the answer you've long been seeking:

    // file: util/thinky.js
    var thinky = require('thinky')({
        // thinky's options
    })
    
    module.exports = thinky;

    Then include it like so:

    // file: models/user.js
    var thinky = require(__dirname+'/util/thinky.js');
    var type = thinky.type;
    
    var User = thinky.createModel("User", {
        id: type.string(),
        name: type.string(),
        age: type.number()
    });
    
    module.exports = User;

    Sincerely yours the man in the mirror (I gotchu bro)