Using Think ORM in various files without reconnecting to database

62 views Asked by At

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?

2

There are 2 answers

0
Parth Patel On BEST ANSWER

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)

0
Deep On

The architecture you are using to create and export thinky models may not be correct.

Refer to this guide for the full suggested architecture. https://thinky.io/documentation/architecture/