'How to use Knex object in other file?
How do I use the knex db object inside other files?
For Example
my index.js
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 ");
});
my User.js
const express = require("express");
const router = express.Router();
const db = require("../index");
router.get("/", async (req, res) => {
console.log(db);
});
module.exports = router;
when am trying to use the db object inside User.js it's not working and giving me an empty object
Solution 1:[1]
You are having cyclic reference between User.js
and index.js
. So db
has not been created yet when you are requesting it in User.js
.
If you really want to keep one globally declared knex instance, you should create separate
db.js
file, which just creates knex and require it in both index.js
and User.js
files.
Solution 2:[2]
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,
},
};
Then crate file db.js and write the code inside file :
const config = require('../../knexfile')
const knex = require('knex')(config);
module.exports = knex;
And finally use where are you use
db(table).select(data).then((result) => { console.log('result', result) });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mikael Lepistö |
Solution 2 | Khairul Islam Tonmoy |