express - How do I expose my initialized bookshelf object to my routes file? -
as first foray nodejs/express/bookshelf please gentle , verbose if possible regards comments/answers.
i'm having hard time figuring out how use express bookshelf, specifically, exposing objects in various modules. bookshelf docs ideally initialization should happen once , initialized bookshelf instance should returned 'throughout library'.
in app.js file create knex/bookshelf connection database, , define model mapping table want..
(app.js)
var knex = require('knex')({ client: 'sqlite3', connection: { filename: '<path-to-my-db' } }); ... var questionroutes = require('./routes/questions'); var app = express(); var bookshelf = require('bookshelf')(knex); // define model var question = bookshelf.model.extend({ tablename: 'questions' }); ... app.use('/', routes); app.use('/api', questionroutes);
in routing file want pull in data using bookshelf...
(routes/quesions.js)
var express = require('express'); var router = express.router(); // on routes end in /questions ... router.get('/questions', function (req, res) { new question() .fetchall() .then(function (questions) { console.log(questions.tojson()); }); });
...but how expose question
model object routing file? or, alternatively, if moved model definition routes, how expose initialized bookshelf
instance?
i haven't been able find useful reference apps bookshelf, code snippets , api docs.
i'm learning node.js , related stuff well; have done follows:
lib/common/bookshelf.js sets bookshelf.js:
var dbconfig = { client: 'sqlite3' // ... }; var knex = require('knex')(dbconfig); var bookshelf = require('bookshelf')(knex); module.exports = bookshelf;
lib/model/question.js file define question model:
var bookshelf = require("../common/bookshelf"); var question = bookshelf.model.extend({ tablename: 'questions' });
lib/routes/question.js:
var question = require('../model/question'); // rest of code.
Comments
Post a Comment