trying to get the array result for mongodb in expressjs - javascript

I'm trying to get a result from MongoDB database return as a response for my GET Request when I make the call I'm getting undefined in the response, I'm able to see the result in console log on the database side of the code. I'm feeling like it might have something to do with it being an array
MongoClient = require('mongodb'),
mongodburl = "mongodb://localhost:27017",
mongo = require('mongodb'),
assert = require('assert');
let method={}
method.insertdata=function(data,collectionpara) {
MongoClient.connect(mongodburl, function (err, db) {
assert.equal(null, err);
let dbo = db.db("hor-usData");
let myobj = data;
dbo.collection(collectionpara).insert(myobj, function (err, result) {
assert.equal(null, err);
console.log("insert data");
db.close();
})
})
}
method.deleteRecords=function(collectionpara) {
MongoClient.connect(mongodburl, function (err, db) {
assert.equal(null, err);
let dbo = db.db("hor-usData");
var myquery = {
title: /^B/
};
dbo.collection(collectionpara).deleteMany(myquery, function (err, obj) {
if (err) throw err;
console.log(obj.result.n + " document(s) deleted");
db.close();
})
})
}
method.getdata=function(collectionpara){
MongoClient.connect(mongodburl, function(err, db) {
if (err) throw err;
let dbo = db.db("hor-usData");
dbo.collection(collectionpara).find().toArray(function(err, result) {
if (err){
return reject(err)
}
console.log('result',result);
return resolve(result);
});
});
}
module.exports = method;
and my router code
let assert = require('assert'),
express = require('express'),
router = express(),
swaggerUi = require('swagger-ui-express'),
database=require('../databaseCon'),
// swaggerDocument = require('./swagger.json'),
utils = require('../utils/utils');
var port = process.env.PORT || 3000;
//get donedeal
router.get('/getDonedeal', function (req, res, next) {
let donedealResult = []
donedealResult=database.getdata('donedeal');
res.send(donedealResult);
});
//get carzone
router.get('/getCarzone', function (req, res, next) {
let carzoneResult = [];
carzoneResult=database.getdata('carzone');
res.send(console.log(carzoneResult));
});
router.get('/cars', function (req, res, next) {
res.router('Mainrouter')
});
router.get('/getCarzone', function (req, res, next) {
var resultArray = []
});
router.listen(port);
//app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
//app.use('/api/v1', router);
module.exports = router;

Related

UnhandledPromiseRejectionWarning: data and salt arguments required

problem: i keep getting the error in title when trying to register a new user only when using postman no idea why.
Also, Proxy problems: Could not proxy request /api/auth/register?hello&world from localhost:3000 to http://localhost:8080/.
Things i've tried to solve proxy was
adding "secure": false in package json.
my auth.js file:
exports.postRegister = async (req, res, next) => {
// User object
const newUser = {
username: req.body.username,
password: req.body.password,
};
// Check if user exists
try {
const user = await User.findOne({ username: newUser.username });
if (user) {
const error = new Error("Username already taken.");
error.statusCode = 422;
return next(error);
}
} catch (error) {
error.statusCode = error.statusCode || 500;
next(error);
}
// creating a hash from the given password
bcrypt.genSalt(12, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(newUser.password, salt, null, async (err, hash) => {
if (err) {
return next(err);
}
try {
// set hashed password as the password field in newUser object.
newUser.password = hash;
// Save newUser
const createdUser = new User(newUser);
await createdUser.save();
// Create jwt token and send
const token = await genToken(createdUser._id, createdUser.username);
res.status(201).json({
success: true,
token,
});
} catch (err) {
err.statusCode = err.statusCode || 500;
next(err);
}
});
});
};
Server.js file:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const helmet = require("helmet");
const cors = require("cors");
require("dotenv").config();
const mailRoutes = require("./routes/mail");
const authRoutes = require("./routes/auth");
const app = express();
app.use(bodyParser.json());
app.use(helmet());
app.use(cors());
// Routes
app.use("/api/mail", mailRoutes);
app.use("/api/auth", authRoutes);
app.use((error, req, res, next) => {
console.log(error.message);
res.status(error.statusCode).json({
error: true,
messages: [error.message],
});
});
mongoose.connect(process.env.DB_URI, (err) => {
if (err) {
console.log(err);
} else {
console.log("DB Connected");
}
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server has started at ${PORT}`);
});
Ok so to anyone who is facing the same problem - i figured it out.
changing from arrow functions to regular function.
apparently bcrypt doesnt accept arrow functions
so instead of:
bcrypt.hash(newUser.password, salt, async => (err, hash){}...
do this:
bcrypt.hash(newUser.password, salt, async function (err, hash){}...

Node express mysql second route call crashes

I am trying to set an API. when the default route is called, with '/', the route can be called several times but the route '/count' can only be called once before crashing with this error:
/Users/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:467:11)
at ServerResponse.header (/Users/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/Users/node_modules/express/lib/response.js:158:21)
at Query.<anonymous> (/Users/server_sql/testingAPI/routes/index.js:25:36)
at Query.<anonymous> (/Users/node_modules/mysql/lib/Connection.js:525:10)
at Query._callback (/Users/node_modules/mysql/lib/Connection.js:491:16)
at Query.Sequence.end (/Users/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
at Query._handleFinalResultPacket (/Users/node_modules/mysql/lib/protocol/sequences/Query.js:139:8)
app.js
const http = require('http');
const cors = require('cors');
const body_parser = require('body-parser');
const databases = require('./connection_management');
const route = require('./routes/index');
const app = express();
app.use(cors());
app.use(body_parser.urlencoded({
extended: true
}));
app.use(body_parser.json());
app.use(databases.connectionsSql);
app.use('/', route);
http.createServer(app).listen(8080, (err) => {
if (!err)
console.log("API ready and HTTP listen on port 8080.");
else
console.log(err)
});
module.exports = app;
route/index.js
var router = require('express').Router();
var connection = require('../connection_management');
router.get('/', function(req, res){
res.send('Default route');
});
function getCo(){
return connection.coSql['test'].pool;
}
router.get('/count', function(req, res){
var pool = getCo();
var countQuery = "SELECT COUNT(data) FROM table WHERE data IS NOT NULL";
try {
pool.getConnection(function(errco, connection){
if(errco) return res.send(errco);
connection.query(countQuery, function(error, result){
if (error) throw error;
else {
try{
connection.release();
return res.send(result);
} catch (err) {
return res.send(err);
}
}
});
})
}catch (err){
return res.send(err);
}
})
module.exports = router;
connection_management.js
const fs = require('fs');
var mysql = require('mysql');
var config = fs.readFileSync('config.json');
config = JSON.parse(config);
const coSql = [];
exports.connectionsSql = (req, res, next) => {
for (let i = 0; i < config.sql.databases.length; i++) {
if (coSql[config.sql.databases[i].name]) {
next();
} else {
coSql[config.sql.databases[i].name] = {};
coSql[config.sql.databases[i].name].pool = mysql.createPool({
host: config.sql.databases[i].host,
user: config.sql.user,
password: config.sql.password,
database: config.sql.databases[i].name});
}
}
next();
}
module.exports.coSql = coSql;
config.js
{
"sql":{
"user": "foo",
"password": "bar",
"databases":[
{
"name": "test",
"host": "localhost"
}
]
}
}
Thanks for your help, fixing and understanding the problem.
In route/index.js:
router.get('/count', function(req, res){
var pool = getCo();
var countQuery = "SELECT COUNT(data) FROM table WHERE data IS NOT NULL";
try {
pool.getConnection(function(errco, connection){
if(errco) throw New Error(errco); // <---- CHANGED THIS.
connection.query(countQuery, function(error, result){
if (error) throw error;
else {
try{
connection.release();
return res.send(result);
} catch (err) {
throw New Error(err); // <---- CHANGED THIS.
}
}
});
})
}catch (err){
return res.send(err);
}
})
You might be calling res.send more than once in your code due to the way you've written you error catching.
I have replaced 2 of your res.send() method calls with thrown errors so that they are caught and dealt with in the final catch block at the bottom.

pendingItem.callback is not a function?

I am trying to view the first row of a table but I get the error
TypeError: pendingItem.callback is not a function
at client.connect
var express = require("express");
const {Pool} = require("pg");
var app = express();
var conStr = "postgres://postgres:password#localhost:5432/postgres";
const pool = new Pool();
app.get("/", function(req, res, next) {
pool.connect(conStr, function(err, client, done) {
if (err) {
console.log("not able to get connection " + err);
res.status(400).send(err);
}
client.query("SELECT * FROM Users where id= $1", [1], function(err, result) {
done();
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});
On Postgres connection Pool using connectionString
First if you are choosing to connect to Postgres using connectionURI, you need to initialize Pool with connectionString param:
const pool = new Pool({
connectionString: connectionString,
})
Then when calling pool.connect you only need to pass callback function:
pool.connect((err, client, release) => {...});
Check documentation on Pooling and different ways of making a connection to Postgres using node-postgres package: here and here
In your case this, it should look like this:
var express = require("express");
const pg = require("pg");
const {Pool} = require("pg");
var app = express();
var conStr = "postgres://postgres:password#localhost:5432/postgres";
const pool = new Pool({
connectionString: conStr
});
app.get("/", function(req, res, next) {
pool.connect(function(err, client, done) {
if (err) {
console.log("not able to get connection " + err);
res.status(400).send(err);
}
client.query("SELECT * FROM Users where id= $1", [1], function(err, result) {
done();
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});

Node.js SyntaxError: Unexpected token

I have defined the routers for the api as follows, one for the post and get,
var bookRouter = express.Router();
bookRouter.route('/Books')
.post(function(req, res) {
var bok = new book(req.body);
console.log(bok);
res.send(bok);
})
.get(function(req, res) {
var query = req.query;
book.find(query, function(err, books) {
if (err)
res.status(500).send(err);
else
res.json(books);
});
});
it throws an error saying '.get(function(req, res) {' Unexpected token .
Node version :
v4.3.0
Parser used :
body-parser
var express = require("express");
var router = express.Ruoter();
router.post("/Books",function(req,res){
var bok = new book(req.body);
console.log(bok);
res.send(bok);
});
router.get("/Book/?id",function(req.res){
var query = req.params.id;
book.find(query, function(err, books) {
if (err)
res.status(500).send(err);
else
res.json(books);
})

Redirection after ajax form Submission from the client side

Hi i am new to nodejs and ajax i m trying to submit a form into database and then set some session variables and then redirect to another page my ajax code on the client side is
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#comp").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { N1: $('#N1').val(), N2: $('#N2').val(), N3: $('#N3').val(), N4: $('#N4').val()
, N5: $('#N5').val(), N6: $('#N6').val(), N7: $('#N7').val(), N8: $('#N8').val(), N9: $('#N9').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
window.location.assign("localhost:3000/User_Creation");
});
});
</script>
and my server side code is as follows i don't know if this is the proper way to do it or not so correct me if i m doing this the wrong way i m putting my whole server file i don't know where i am going wrong
var express = require('express');
var mongo = require('mongodb').MongoClient;
var app = express();
var path = require('path');
var bodyParser = require("body-parser");
var url = 'mongodb://localhost:27017/test';
var assert = require('assert');
var MongoClient = require('mongodb').MongoClient;
var session = require("express-session");
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = []
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({resave: true, saveUninitialized: true, secret:'iasugdhasjb981234781924789', cookie: { maxAge: 60000 }}));
app.use(bodyParser.json());
app.get('/index', function (req, res) {
if(!req.session.userId)
{
res.render('index.ejs');
}
else
{
res.redirect('/welcome');
}
});
app.post('/index', function (req, res) {
var N1 = req.body.firstname;
var N2 = req.body.lastname;
MongoClient.connect(url, function(err, db) {
if (err) {
throw err;
}
db.collection('OB').find({user_name:N1},{password:N2}).toArray(function(err, result) {
if (err) {
throw err;
}});
});
});
var resultArray = [];
app.post('/login', function(req, res, next) {
var N1 = req.body.N1;
var N2 = req.body.N2;
MongoClient.connect(url, function(err, db) {
if (err) {
throw err;
}
db.collection('OB').find({user_name:N1,password:N2}).toArray(function(err, result) {
if (err) {
throw err;
}
resultArray=result;
try{
req.session.userId = result[0]._id;
req.session.userType = result[0].type;
if(result[0].type=="root")
{
res.redirect('/New_Company');
}
else
{
res.redirect('/welcome');
}
}
catch(e){
res.redirect('/404_Error');
}
});
});
});
app.get('/404_Error',function(req, res){
res.render('404_Error.ejs');
});
app.get('/New_Company',function(req, res){
if(!req.session.userType){
res.redirect('/404_Error');
}
else{
res.render('create_company.ejs');
}
});
app.post('/New_Company',function(req, res){
if(!req.session.userType){
res.redirect('/404_Error');
}
if(req.session.userType!="root"){
res.redirect('/404_Error');
}
var item = {
company_name: req.body.N1,
Comp_currency: req.body.N2,
start_time: req.body.N3,
end_time: req.body.N4,
comp_country: req.body.N5,
phone_no: req.body.N6,
total_locations: req.body.N7,
time_zone: req.body.N8
};/*
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if (err) {
throw err;
}
db.collection('company').find({company_name:req.body.N1}).toArray(function(err, result) {
if (err) {
throw err;
}
res.redirect('/404_Error');
});
});
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('company').insertOne(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if (err) {
throw err;
}
db.collection('company').find({company_name:req.body.N1}).toArray(function(err, result) {
if (err) {
throw err;
}
console.log(result);
req.session.comp_id = result[0]._id;
res.redirect('/User_Creation');
});
});
});
});*/
console.log('Successfully Executed');
});
app.get('/User_Creation', function(req, res){
res.render('create_user.ejs');
});
app.get('/logout',function(req,res){
req.session.destroy();
res.redirect('/index');
});
app.get('/welcome',function(req, res){
if(!req.session.userId)
{
res.redirect('/404_Error');
}
else
{
res.render('login.ejs',{resultArray:resultArray,id:req.session.userId});
}
});
app.get('/', function(req, res){
res.send('DEFAULT PAGE');
});
app.get('/location', function(req, res){
res.render('location_details.ejs');
});
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected :%s sockets connected',connections.length);
socket.on('disconnect',function(data){
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets connected',connections.length);
});
socket.on('send message',function(data){
console.log(data);
io.sockets.emit('new message',{msg:data});
});
});
server.listen(3000);
console.log("running");
thanks....
Add http at the beginning of the URL:
window.location.assign("http://localhost:3000/User_Creation");

Categories

Resources