Connect to database from server.js file on Angular and NodeJS app - node.js

I have two files in my angular project: server.js and db_connection.js. I'm hosting the project on Heroku.
The server.js currently runs because, in my package.json, I have "start": "node server.js"
I want to connect to the database as well, but I want to put that in a separate file called db_connection.js. How should I go about making sure the code in that file runs? Do I call it from server.js? If so, how so?
My files:
server.js:
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(__dirname + '/dist/my-app'));
app.listen(process.env.PORT || 8080);
// PathLocationStrategy
app.get('*', function (req, res) {
res.sendFile('dist/my-app/index.html' , { root : __dirname});
});
console.log('Console Listening')
db_connection.js:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "my_server.net",
user: "my_username",
password: "my_password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

You could do something like this.
server.js
const express = require('express');
const app = express();
const path = require('path');
const db = require('./db_connection')
app.use(express.static(__dirname + '/dist/my-app'));
app.listen(process.env.PORT || 8080);
// PathLocationStrategy
app.get('*', function (req, res) {
res.sendFile('dist/my-app/index.html' , { root : __dirname});
});
app.get('/getSomethingFromDB', db.getSomethingFromDB)
app.post('/postSomethingToDB', db.postSomethingToDB)
console.log('Console Listening')
db_connection.js
const mysql = require('mysql')
const con = mysql.createConnection({
host: "my_server.net",
user: "my_username",
password: "my_password",
database: 'my_db_name'
});
con.connect( err => {
if (err) throw err;
console.log("Connected")
});
module.exports = {
getSomethingFromDB: (req, res) => {
const getQuery = `SELECT * FROM some_table WHERE condition`
con.query(getQuery, (error, results, fields) => {
if (error) {
return res.status(500).send("DB Error")
} else {
return res.status(200).send(results)
}
})
},
postSomethingToDB: (req , res) => {
// Your code for post requests
},
// Similarly other functions
}

Related

How can I seperate different routes in different files in nodejs?

I'm learning reactjs and nodejs and with help of fellow stackoverflow members i've been able to successfully create the front end. Now i'm working on the back end in nodejs. Nodejs is also working fine but right now all my code is in single index.js file and i'm worried that its going to get bigger and bigger.
I just want to know how can I move stuff from index.js to seperate files ? For eg. I have catgeories (add,modify,delete list) then same for products, users etc.
My routes are like:
/add-category
/mod-category
/del-category
/categories
/add-user
/mod-user
/del-user
/users
/add-product
/mod-product
/del-product
/products
They're all working fine, just that they're in a single index.js file. How can I move routes of products into products.js and subsequently categories into categories.js and users into users.js ?
Some of my code is following as to how my index.js is:
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "shop",
});
app.get("/admin/categories", (req, res) => {
db.query("SELECT * FROM categories ORDER BY catg_name", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});
app.put("/admin/mod-category", (req, res) => {
const id = req.body.id;
const name = req.body.name;
const description = req.body.description;
const status = req.body.status;
db.query(
"UPDATE categories SET catg_name = ?, catg_description = ?, catg_status = ? WHERE catg_id = ? LIMIT 1",
[name, description, status, id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.delete("/admin/del-category/:id", (req, res) => {
const id = req.params.id;
db.query(
"DELETE FROM categories WHERE id = ? LIMIT 1",
[id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.listen(3001, () => {
console.log("Server is running on port 3001");
});
Any help is appericiated.
Thanks.
you can create a separate file for each collection.
categories routes file
const router = require('express').Router();
router.get('/categories/:id', (req, res) => {
// get a category by ID
});
router.post('/categories', () => {
// create a category
});
module.exports = router;
then a file for the products
const router = require('express').Router();
router.get('/products/:id', (req, res) => {
// get a product by id
});
router.post('/products', () => {
// create a product
});
module.exports = router;
after that import the exported routers to your index file and use them with
app.use() function
const express = require('express');
const productsRouter = require("./src/productsRouter");
const categoriesRouter = require("./src/categoriesRouter");
const app = express();
app.use(productsRouter);
app.use(categoriesRouter);
In this particular case, you can define each endpoint action as a file function.
You can do a categories.js file with any function that you need
const database = require('./connection.js')
const CATEGORIES = {
edit_categories : (req, res) => {
...
},
delete_categories : (req, res) => {
...
},
find_categories : (req, res) => {
...
}
}
module.exports = CATEGORIES
And apart you can define your connection.js
const mysql = require("mysql");
const database = () =>{
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "shop"
});
return db;
}
module.exports = database();
And then use it all
const express = require("express");
const app = express();
const cors = require("cors");
const CATEGORIES = require('./categories.js');
app.use(cors());
app.use(express.json());
app.get("/admin/categories", CATEGORIES.find_categories );
app.put("/admin/mod-category", CATEGORIES.edit_categories );
app.delete("/admin/del-category/:id", CATEGORIES.delete_categories );
app.listen(3001, () => {
console.log("Server is running on port http://127.0.0.1:3001");
});
Obviously there is some many different ways for structure your project (you can separate routes, modeling and views on that way)

Router.use() requires a middleware function but got a ' + gettype(fn))

one question. I am making an api with node,express and mysql.
And there seems to be an error when I run nodemon.
If anyone knows anything, it would be appreciated.
Error:
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
My index.js:
const express = require('express')
const app = express()
const routes = require("./routes/transactions")
//Settings
app.use('port', process.env.PORT || 3000)
//Middlewares
app.use(express.json())
//Routes
app.use("/", routes.transactions)
//Crear servidor con el puerto
app.listen(app.get('port'), () => {
console.log('Hola Mundo', app.get('port'))
})
module.exports = app;
My routes/transactions.js
const express = require('express');
const router = express.Router();
const mysqlConnection = require('../database');
router.get('/transactions', (req, res) => {
mysqlConnection.query('SELECT * FROM transactions', (err, rows, fields) => {
if(!err) {
res.json(rows)
} else {
console.error(err)
}
});
});
exports.transactions = router
My database.js
const mysql = require('mysql');
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'operations',
})
mysqlConnection.connect(function(err){
if(err) {
console.log(err);
return
} else {
console.log('Db is connected')
}
})
module.exports = mysqlConnection;
You are mistakenly using app.use() instead of app.set().
Change this:
app.use('port', process.env.PORT || 3000)
to this:
app.set('port', process.env.PORT || 3000)
The error comes because you're passing a string or number to app.use() where it expects a middleware function reference.
It seems like you should have had a stack trace for this error (if you learn how to interpret it) that points to the exact line of code (a few steps up the stack) causing the problem which should simplify debugging next time.
I think the error here is resulting from the overload of app.use():
You can use this function in two ways, to use middleware and routes.
routes/transactions.js should be altered to the following:
const router = express.Router();
const mysqlConnection = require('../database');
router.get('/transactions', (req, res) => {
mysqlConnection.query('SELECT * FROM transactions', (err, rows, fields) => {
if(!err) {
res.json(rows)
} else {
console.error(err)
}
});
});
exports.transactions = router
In index.js:
const express = require('express')
const app = express()
const routes = require("./routes/transactions")
//Settings
app.use('port', process.env.PORT || 3000)
//Middlewares
app.use(express.json())
//Routes
app.use("/", routes.transactions)
//Crear servidor con el puerto
app.listen(app.get('port'), () => {
console.log('Hola Mundo', app.get('port'))
})
module.exports = app;
This would run the code in the 'get' endpoint in 'routes/transactions.js' when you navigate to localhost:<port>/transactions.

How to use exec() in nodejs

I have this procedure xyz_users_list and it return list of users with exec xyz_users_list but how do i use it in nodejs app?
Code
index.js
'use strict';
const express = require('express');
const app = express();
const mysql = require('mysql');
var connection = require('express-myconnection');
require('dotenv').config();
app.use(
connection(mysql, {
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
}, 'request')
);
app.get('/', (req, res) => {
return res.sendFile(__dirname + '/index.html');
});
//all users
var Users = require('./routes/Users');
app.get('/users', Users.list);
Users.js
'use strict';
var response = require('../res');
const { exec } = require('child_process');
exports.list = function(req, res) {
req.getConnection(function(err, connection) {
connection.query(exec('xyz_users_list'), function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
this code returns:
TypeError: Cannot read property 'query' of undefined
If I use code below it works just fine but since i want to use exec it's returning error.
exports.list = function(req, res) {
req.getConnection(function(err, connection) {
connection.query('SELECT * FROM `users`', function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
any idea?
Update
here is result of my exec xyz_users_list in SQLQuery
Your connection is coming as undefined so it is showing this error. Try this version
const sql = require("mssql");
exports.list = async function(req, res) {
const connection = await sql.connect("connectionString");
const results = await connection.request().execute("xyz_users_list");
}
Need to add the corresponding return statements but you will get an idea.

Node js & mongoDB - TypeError: db.collection is not a function

I am trying to post data from POSTMAN to an external database that I created on mLab but I am getting the error db.collection is not a function.
There is a similar question thread but the answer is incomplete and doesn't save any keys/values I put into postman to mLab. The code that I am trying to make work is from this tutorial: https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
My Code:
Server.js
const express = require('express'); // Load routes application
const MongoClient = require('mongodb').MongoClient; //Load database connection application
const db = require('./config/db');
const app = express(); // Assign express app a variable
const port = 8000; //Set local port value for server
const bodyParser = require('body-parser'); // **This has to come BEFORE routes
var assert = require('assert'); // ?
var databaseURL ='mongodb://external:api#ds123312.mlab.com:23312/soundfactory';
app.listen(port, () => {
console.log('')
console.log('We are live on ' + port);
console.log('')
});
MongoClient.connect(databaseURL, function(err, db) {
assert.equal(null, err);
console.log("API has succesfully connected to Sound Facotry mlab external database.");
console.log('')
db.close();
});
app.use(bodyParser.urlencoded({ extended: true }))
require('./app/routes')(app, {}); //Must come AFTER express w/ body parser
db.js
module.exports = {
url : 'mongodb://external:api#ds123312.mlab.com:23312/soundfactory'
};
index.js
const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
noteroutes(app,db);
};
note_routes.js
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};
partially correct code
server.js (code that partially works & doesn't throw the db.collections error like my original server.js file )
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({extened:true}));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err)
//require('./app/routes')(app,{});
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
})
Remove the node_modules folder and change mongodb version of your package.json
"mongodb": "^2.2.33"
and run below code :
npm install
change to this require('mongodb').MongoClient;

Dynamic CRUD functions with Node, Express and Pug

Hi I am new to backend node applications and I am trying to create a clean API driven node.js app without frameworks by working with scripts and pug template engine.
I have created a serve.js file with all the necessary code:
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
const bodyParser = require("body-parser");
var mongodb = require("mongodb");
const MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var indexRoutes = require('./routes/index');
var thePort = process.env.PORT || 5000;
var SECTIONS_COLLECTION = "sections";
//make results available as json
app.use(bodyParser.json());
//External database identifier
var db;
//Path to the database with URI
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2orjhen7knanjpfmd7#ds014586.mlab.com:19986/heroku_fmvc5nhk';
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(dbpath, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
//static folder directory
app.use(express.static(__dirname + '/dist'));
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
//set up routes directory
app.use('/', indexRoutes);
// Views and Template Engine
//app.set('views', __dirname + './views');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// sections API ROUTES:
/* "/api/sections"
* GET: finds all sections
* POST: creates a new contact
*/
app.get("/api/sections", function(req, res) {
db.collection(SECTIONS_COLLECTION).find({}).toArray(function(err, docs) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.status(200).json(docs);
}
});
});
app.post("/api/sections", function(req, res) {
var newContact = req.body;
if (!req.body.name) {
handleError(res, "Invalid user input", "Must provide a name.", 400);
}
db.collection(sections_COLLECTION).insertOne(newContact, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new contact.");
} else {
res.status(201).json(doc.ops[0]);
}
});
});
/* "/api/sections/:id"
* GET: find contact by id
* PUT: update contact by id
* DELETE: deletes contact by id
*/
app.get("/api/sections/:id", function(req, res) {
db.collection(SECTIONS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get contact");
} else {
res.status(200).json(doc);
}
});
});
app.put("/api/sections/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
db.collection(SECTIONS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update contact");
} else {
updateDoc._id = req.params.id;
res.status(200).json(updateDoc);
}
});
});
app.delete("/api/sections/:id", function(req, res) {
db.collection(SECTIONS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
if (err) {
handleError(res, err.message, "Failed to delete contact");
} else {
res.status(200).json(req.params.id);
}
});
});
In my views\about.pug template I reference my JSON object's contents.
//--about.pug
extends index.pug
block div.root
h2= #{about.heading}
h3= #{about.summary}
p #{about.content}
In my routesroutes/index.js I have pre-existing "flat" examples with pug then one dynamic about example:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render(
'index',
{
title: 'Welcome to Awesome Place',
header: 'Home',
summary: 'This is my home. It can\'t be any simpler'
}
)
})
Dynamic example:
//About
router.get('/about', function (req, res) {
//retrieve all home from Mongo
db.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.render('about', {})
console.log(result)
}
}
})
The above is returning a db is not defined error.
If var indexRoutes = require('./routes/index'); is required as part of my server.js file, why can't it find the value of db?
UPDATED CODE (TOO MANY ERRORS)
//server.js
//APP Dependences
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var indexRoutes = require('./routes/index');
var bodyParser = require("body-parser");
//PORT
var thePort = process.env.PORT || 5000;
// Views and Template Engine
//app.set('views', __dirname + './views');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//Documents
app.use(bodyParser.json());
//static folder directory
app.use(express.static(__dirname + '/dist'));
//set up routes directory
app.use('/', indexRoutes);
// Catch errors
app.use(function(req, res, next) {
res.status(404).sendFile(process.cwd() + '/app/views/404.htm');
});
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
var mongodb = require("mongodb");
const MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var SECTIONS_COLLECTION = "sections";
//External database identifier
var db;
//Path to the database with URI
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovanbfd7knanjpfmd7#ds019986.mlab.com:19986/heroku_fmvc5nhk';
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(dbpath, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
//db.js
var express = require('express');
var mongodb = require("mongodb");
var MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var assert = require('assert');
//Path to the database with
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovahen7knanjpfmd7#ds019986.mlab.com:19986/heroku_fmvc5nhk';
//Get the section
var SECTIONS_COLLECTION = "sections";
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(dbpath , function(err, database) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(database);
});
}
module.exports = connectMongo;
//routes/index.js
var express = require('express');
var router = express.Router();
var connectDB = require ('../db')
router.get('/', function (req, res) {
res.render(
'index',
{
title: 'Welcome to Awesome Place',
header: 'Home',
summary: 'This is my home. It can\'t be any simpler'
}
)
})
connectMongo(function(database){
//About
router.get('/about', function (req, res) {
//retrieve all home from Mongo
database.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.render('about', {})
console.log(result)
}
}
})
}
router.get('/work', function (req, res) {
res.render(
'work',
{
title: 'Work, Work, Work , Work...',
header: 'Work life',
summary: 'My first work for this bitch',
imgUrl: '/img/firaz.jpg'
}
)
})
router.get('/contact', function (req, res) {
res.render(
'contact',
{
title: 'Contact Me Any Time',
header: 'Contact Me Any Time',
summary: 'Fill the form below to be contacted'
}
)
})
module.exports = router;
Because db variable is not global by requiring var indexRoutes = require('./routes/index'); you are importing the objects from routes/index file to server not the other way around.
what you can do is make your db variable global global.db and access it anywhere or create a seperate file for mongo db connection and require that in routes file
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(db);
});
}
module.exports = connectMongo;
This github Repo got good structure for mongoDB
https://github.com/OmarElGabry/chat.io

Resources