How to use exec() in nodejs - node.js

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.

Related

Can't insert on MongoDB

I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
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': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!

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

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
}

TypeError: Cannot read property 'then' of undefined node js

TypeError: Cannot read property 'then' of undefined
Can you help me fix this? Thank you.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017',
function(err, db) {
if(err){
throw err;
}else{
console.log("connected");
}
})
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));
app.post('/post-feedback', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
db.collection('feedbacks').insertOne(req.body);
});
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
});
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
TypeError: Cannot read property 'then' of undefined
Can you help me fix this? Thank you.
The following approach should get you started but should not use this for production (Reference: How do I manage MongoDB connections in a Node.js web application?). Read through for another production starters.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = function() {
return new Promise((resolve, reject) => {
mongodb.MongoClient.connect('mongodb://localhost:27017',
function(err, db) {
if(err){
return reject(err);
}else{
return resolve(db);
}
});
});
}
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));
app.post('/post-feedback', function (req, res) {
dbConn()
.then(function(db) {
delete req.body._id; // for safety reasons
db.collection('feedbacks').insertOne(req.body);
res.send('Data received:\n' + JSON.stringify(req.body));
})
.catch(err => {
console.log(err)
res.send('Error');
})
});
app.get('/view-feedbacks', function(req, res) {
dbConn()
.then(function(db) {
db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
})
.catch(err => {
console.log(err);
res.status(500).json({});
});
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
Production Starter:
Ideally you will have something like following say in a file db.js
let mongoClient = require('mongodb').MongoClient,
logger = require('winston');
function DATABASE() {
this.dbObj = null;
this.myCollection = null; // You will need to add more collections here
}
DATABASE.prototype.init = function (config, options) {
let self = this;
self.config = config; //can pass a config for different things like port, ip etc.
self.logger = logger;
return new Promise(function (resolve, reject) {
if (self.initialized) {
return resolve(self);
}
let connectionUri = "mongodb://localhost:27017"; //self.config.mongo.connectionUri;
mongoClient.connect(connectionUri, {native_parser: true}, function (err, db) {
if (err) {
reject(err);
}
else {
self.dbObj = db;
self.myCollection = db.collection('myCollection');
self.initialized = true;
self.logger.info("db init success");
return resolve(self);
}
});
});
};
var dbObj = null;
var getdbObj = function () {
if (!dbObj) {
dbObj = new DATABASE();
}
return dbObj;
}();
module.exports = getdbObj;
In your main app start file you will have something like:
let dbObj = require('./db.js');
dbObj.init()
.then(db => {
console.log('db initialized successfully');
//db.dbObj.collection('myCollection').find()
//or
//db.myCollection.find() because this has been already initialized in db.js
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));
app.post('/post-feedback', function (req, res) {
delete req.body._id; // for safety reasons
db.dbObj.collection('feedbacks').insertOne(req.body);
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.get('/view-feedbacks', function(req, res) {
//db.collection('feedbacks')
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' )
})
.catch(err => console.log(err));
Try this, dbConn is not promise
app.post('/post-feedback', function (req, res) {
mongoose.connection.db.collection('feedbacks', function (err, collection) {
collection.insertOne(req.body);
res.send('Data received:\n' + JSON.stringify(req.body));
});
// OR
const Model = mongoose.model('feedbacks');
let model = new Model();
model = Object.assign(model, req.body);
model.save().then((result) => {
res.send('Data received:\n' + JSON.stringify(req.body));
});
});
Its working .
If you are getting any TypeError (UnhandledPromiseRejectionWarning: TypeError: db.collection is not a function) form mongodb. Just change the version of mongodb to -
"mongodb": "^2.2.33"
"use strict"
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/feedback';
// no need to call then() yet
var dbConn = MongoClient.connect(url);
app.set('port', 5000);
app.listen(app.get('port'), function() {
console.log('feedback is running on port', app.get('port'));
});
app.get('/view-feedback', function(req, res, next) {
// the connection is opened
dbConn.then(function(db) {
// var dbo = db.db("feedback");
db.collection('feedback').find({}).toArray().then(function(docs) {
// return docs;
res.json(docs)
});
});
});

Express.js nested routes without parameters

I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};

Mongodb Insert data API no respone

I need an API to insert data from android to mongodb , I follow this ,the code can run , have NO error , and I use POSTMAN try to post some data , it always say could not get any respone , seem to have an error connecting to 192.168.1.105:3000/songs
but I can use find all api and findByID.
This took me hours , please help , so depress :(
app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.get('/songs',songs.addSong);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXX:XXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.addSong = function(req, res) {
var song = req.query;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
{console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
Okay so I changed a few things in your code. I'm successfully getting the request body in the app.js file. Do have a look at the code.
route.js
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://localhost:27017/test";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
Notice that I have changed the URI to localhost, so change it again to the one you specified.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
songs = require('./routes/route');
app.post('/songs', function(req, res) {
console.log("Request.Body : " + JSON.stringify(req.body));
if (!req.body) return res.sendStatus(400);
songs.addSong(req, res);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
Since your only problem was that you weren't able to get the request body. You'll be able to get it with this code.
Also since your app.get('/songs',songs.addSong); is of type GET, you'll not be able to send POST Data through it. So change it to
app.post('/songs',songs.addSong);
Hope this helps.

Resources