Guide: Leveraging the Knex object in a separate file

How can I effectively utilize the knex db object across multiple files?

As an illustration

In my main index.js file:

const app = require("express")();
const cors = require("cors");
const bodyParser = require("body-parser");
const user = require("./routes/User");
const product = require("./routes/Product");

//-----------------
const db = require("knex")({
  client: "pg",
  connection: {
    host: "127.0.0.1",
    user: "postgres",
    password: "",
    database: "Razer"
  }
});

//-----------------
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//-----------------
app.use("/user", user);
app.use("/product", product);

//-----------------
module.exports = db;

//-----------------
app.listen(5000, () => {
  console.log("App listening on PORT 5000 ");
});

In my User.js file:

const express = require("express");
const router = express.Router();
const db = require("../index");

router.get("/", async (req, res) => {
  console.log(db);
});

module.exports = router;

However, when attempting to access the db object within User.js, it returns an empty object instead of the expected data.

Answer №1

A circular reference exists between User.js and index.js. This means that the database connection db may not have been established when it is being accessed in User.js.

If you prefer to use a single globally defined Knex instance, consider creating a separate file named db.js solely for initializing Knex. Then, simply require this file in both index.js and User.js.

Answer №2

Database Configuration in knexfile.js

const path = require('path');
    
    module.exports = {
      development: {
        client: 'mysql',
        connection: {
          host: 'localhost',
          port: 3306,
          user: 'root',
          password: '',
          database: 'e_transport',
        },
        migrations: {
          directory: path.join(__dirname, './src/migrations'),
        },
        useNullAsDefault: true,
      },
    
      production: {
        client: 'mysql',
        connection: {
          host: 'localhost',
          port: 3306,
          user: 'root',
          password: '',
          database: 'e_transport',
        },
        migrations: {
          directory: path.join(__dirname, './src/migrations'),
        },
        useNullAsDefault: true,
      },
    };

Create a new file named db.js with the following code:

const config = require('../../knexfile')
const knex = require('knex')(config);

module.exports = knex;

To use the database, include this line of code where needed:

db(table).select(data).then((result) => { console.log('result', result) });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the optimal technology for maximum persistence

We are currently running an application server on nodejs and looking to switch out our existing MySQL persistence technology. Our main considerations for the replacement are various NoSQL options such as CouchDB, MongoDB, Redis, Riak, and more. The data si ...

Is there a reason why the layout.jade isn't functioning properly?

I have encountered an issue with my configure file: The layout.jade is not working properly, even though the jade itself is functioning correctly. I have verified this using Chrome and confirmed that the layout HTML is not being loaded into the page. modu ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my databa ...

Struggling to understand the process of retrieving information from an Axios promise

For my current project, I've been experimenting with using Axios to retrieve JSON data from a json-server to simulate a database environment. While I can successfully display the retrieved data within the .then() block of the Axios function, I'm ...

Obtaining Spotify API access token using JavaScript code on the front end

I've developed a web application that enables users to generate a list of songs by artists related to a selected artist. The goal is to link the user's Spotify account and create a playlist based on this generated song list, which requires obtain ...

Using Bookshelf, Knex, and MySQL to store information about a collection of items

I'm facing a dilemma when it comes to using the Bookshelf model to insert data into the database in this particular scenario: The libraries I am working with include knex, bookshelf, express, body-parser, and a MySQL database In my database, there i ...

NodeJS - Retrieving image file size from source shows inaccurate results

I have a simple query regarding the size discrepancy of files when read using fs.readFileSync, particularly when the source path points to an image or non-text file. For instance: fs.writeFileSync(outputPath, fs.readFileSync(source, 'utf8')); ...

Is it necessary to specify the server-side script within the "routes" directory?

I'm currently developing a NodeJS Express application and from what I gather, the communication between the server and client is achieved by incorporating an AJAX script in a JavaScript file (on the client-side) and implementing a listener function (f ...

Having trouble getting the convert-multiple-files npm package to function properly on an Elastic Beanstalk environment running Amazon Linux

Following a successful deployment, I encountered an issue with my file conversion script when attempting to convert files as outlined in the documentation. The script works flawlessly on both a local Windows 10 machine and Ubuntu 20.04 LTS. const { conv ...

Configuring API paths based on environment variables with Express and Angular deployed on Heroku

I have a specific task I need help with, and I'll provide more details below. In my main Angular JavaScript file, I need to define a string that determines the server path for my app depending on whether it's in a production or staging environme ...

What is the best way to retrieve the current directory in npm scripts?

Consider a scenario where the package.json for my projects is located as follows: project |- package.json Now, imagine that I run an npm script from a different location within the project structure: project |- package.json |- some |- nested |- ...

Having trouble with npm? It's showing a "Response timeout" error when attempting to fetch data from https://registry.npmjs

Whenever I attempt to install a package, I encounter the following error message. I've exhausted all my options, can someone please assist me? npm ERR! Response timeout occurred when attempting to fetch https://registry.npmjs.org/base-config-proc ...

The issue of passing a sequelize model instance to a service within an express.js environment has been causing complications

I am struggling to access the findById function of CRUDService in ItemService. While I am able to get a response from the readAll function, I am facing issues with the findById function. It seems that the dao object being passed to CRUDService from ItemSer ...

Issues with triggering the success block in AngularJS and Node.js Express when using $http.get

As a beginner in the world of AngularJS and Node.js, I'm facing an issue with my $http.get method. The problem is that the success callback block does not get executed when the request is successful, whereas the error callback works just fine when the ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Issue: Encountered an error when attempting to use the multer module

Hello experts, I am venturing into backend technology for the first time. As part of my project, I am trying to upload files and text to my database using nodejs and mongoDB. However, I keep encountering an error message that is impeding my progress. I wou ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

The error thrown by Mongoose, stating "TypeError: Cannot read property 'catch' of undefined," is not caught after the data is saved

After updating to Mongoose version 5.0.15, I encountered an error that says TypeError: Cannot read property 'catch' of undefined when trying to save my object with errors found, even though everything was working fine on Mongoose version 4.13.11. ...

Converting a Postgres column into a JSON column

Is it possible to transform the integer column foo into a json array column bar? The provided solution seems ineffective as m2 is not recognized as a valid json expression... UPDATE mytable SET bar='[m2.foo]' FROM ( SELECT m.foo FROM mytable ...