mongodb not insert the full array - javascript

I use the following to insert 499 entry into a subdocument, I get the data from an array
my code is something like this (i will shortcut the array because it too long)
var bodyParser = require('body-parser');
var express = require("express");
var path = require("path");
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var app = express();
var url = "mongodb://<username>:<password>#ds157342.mlab.com:57342/heroku_4p9ggb81";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var entery = ['غبة خاتون','حي الربيع','المغرب','القاهرة','الصليخ',.........];
var collection = db.collection('customers');
for (var i = 0 ; i<entery.length; i++){
var query = {"_id" : ObjectId(),"value": entery[i],"key": i}
collection.updateOne({"_id":ObjectId("59ccdf34aabdd50011258cbf")},{ "$push": { "lookupdata": query }},{ upsert: true },
function (err, result) {if (err) throw err;db.close();
});
console.log(i + "- " + entery[i] + " add data finsh ");}
app.listen(process.env.PORT || 3000, function (){
console.log("server is started");});
my document structure like this
{
"_id" : ObjectId("59cce9fcaabdd50011258cc0"),
"formorder" : 1,
"isDisplayOnList" : true,
"issystemfield" : false,
"isMandatory" : false,
"description" : "-",
"labelname" : "name",
"displayname" : "name",
"fieldtype" : "list",
"formname" : "people",
"lookupdata" : [
{
"value" : "test",
"key" : "1",
"id" : "669c78c9-d086-442c-954b-d6d3f861664b"
}
],
}
my problem that my code does not insert all the 499 entry from the array into the "lookupdata" object, it just enters 50 entry and sometimes just 120 etc, I try to change the way I write this code many times but the problem still the same.

You are inserting/updating the data without using a callback, use async module.
`var bodyParser = require('body-parser');
var express = require("express");
var path = require("path");
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var async = require('async');
var app = express();
var url = "mongodb://<username>:<password>#ds157342.mlab.com:57342/heroku_4p9ggb81";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var enteries = ['غبة خاتون','حي الربيع','المغرب','القاهرة','الصليخ',.........];
var collection = db.collection('customers');
async.eachOf(enteries, function(entery, key, callback){
var query = {"value": entery,"key": key}
collection.updateOne({"_id":ObjectId("59ccdf34aabdd50011258cbf")},{ "$push": { "lookupdata": query }},{ upsert: true },
function (err, result) {if (err) throw err;db.close();
});
}, function(err){
if(err) throw err;
});
console.log(i + "- " + entery[i] + " add data finsh ");}
app.listen(process.env.PORT || 3000, function (){
console.log("server is started");});`

Related

Port Errors running node.js application

i cloned an node.js application and , to set up, i did an npm install and npm install -g nodemon , i wanted to run it locally on port 3000, so in my app.js file i added
app.listen(3000, () => console.log('Server running on port 3000!'))
and then i tried to run it by using node app.js but i am getting this errors
this is my app.js file
var express = require('express');
var engine = require('ejs-locals');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var request = require('request');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var routes = require('./routes/index');
var testgrid = require('./routes/testgrid');
var hsdes_query = require('./routes/hsdes_query');
var find_coverage = require('./routes/find_coverage');
var url = "mongodb://127.0.0.1:27017/onegrid_int";
var config = require('./config');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var manual_ti_payload_template = {
"attributes": [],
"blackList": "string",
"description": "string",
"endDate": "2019-02-03T21:28:12.567Z",
"id": "string",
"itemId": "string",
"key": "string",
"name": "ascii string",
"namespace": "ascii string",
"ownerIdsid": "string",
"planningAttributes": [],
"resources": [],
"resourcesVersions": [],
"startDate": "2019-02-03T21:28:12.567Z",
"type": "manualitem",
"version": 0,
"whiteList": "string"
}
app.post('/updategtaproc', function(req, res){
console.log("updategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + req.body.name,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
res.send(body)
});
});
app.post('/createnupdategtaproc', function(req, res){
console.log("createnupdategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var ti_payload = Object.assign({}, manual_ti_payload_template);
ti_payload.name = req.body.expected;
ti_payload.description = req.body.description;
ti_payload.ownerIdsid = username;
ti_payload.namespace = "vtt-gve-gqe"
console.log(ti_payload)
request.post( {
url : 'https://gta.intel.com/api/tp/v1/testitems',
headers : {
"Authorization" : auth
},
json: ti_payload,
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
if (body && body.itemId) {
console.log("Test case created successfully", body.itemId);
var itemId = body.itemId;
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + body.itemId,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
console.log("Test Procedure Uploaded Successfully");
body['itemId'] = itemId
res.send(body)
});
} else {
console.log("Failed to Create Test Case");
res.send({"message":"Failed To Create Test Case"})
}
});
});
app.post('/getgriditems/:id', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid_int//getgriditems/:id unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "griditems"
var collection = db.collection(collection_name);
var objectIdArr = [];
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
item = req.body[key];
try {
objectIdArr.push(ObjectId(String(item)));
}
catch (err)
{
// Invalid Object ID
}
}
}
collection.find({"_id" : {"$in" : objectIdArr }}).toArray(function(err, griditems) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get grid items')
}
else
{
var paths = []
for ( var r in griditems){
//console.log('path :', result[r]['path'])
paths.push(griditems[r]['path'].join(",") + ',' + griditems[r]['testItem']['itemId'])
}
console.log("paths", paths)
var global_result_collection = db.collection("onegrid-global-results");
global_result_collection.find({"full_path" : {"$in" : paths }}).toArray(function(err, results) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get test results')
}
else
{
var metadata = {}
metadata['griditems'] = griditems
metadata['results'] = results
console.log("test_results", results)
res.send(metadata);
db.close();
}
});
}
});
}
});
});
app.post('/get_all_tags', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection = db.collection('user_tags');
collection.find().toArray(function(err, tags) {
if(err)
{
console.log('onegrid/manual_tests/error getting documents from collection')
}
else
{
var tag_type_ar = tags.map(a => a.type_tag);
//console.log('onegrid/manual_tests/number_of_docs/', tests.length)
//console.log('onegrid/manual_tests/tags/', tags_name)
res.send(tag_type_ar);
db.close();
}
});
}
});
});
app.post('/getsettags', function(req, res){
//console.log('body: ' + JSON.stringify(req.body));
var url = "mongodb://127.0.0.1:27017/onegrid";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/getsettags/unable to connect to mongodb')
}
else
{
var objectId = ObjectId(req.body.id);
var collection = db.collection('gve_manual_testitems');
if(req.body.op == 'set_add') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
if(result['tags'] && result['tags'].indexOf(req.body.newtag) != -1) {
res.send(result);
db.close();
}
else {
if(result['tags'])
{
result['tags'].push(req.body.newtag)
}
else
{
result['tags'] = [req.body.newtag];
}
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags added successfully to test item');
var test_tags = result;
if(!req.body.skip_tag_source_update) {
var user_tags = db.collection('user_tags');
var type_tag = req.body.newtag;
var type = req.body.newtag.split(":")[0]
var tag = req.body.newtag.split(":")[1]
var tag_obj = {'type':type, 'tag': tag, 'type_tag' : type_tag}
user_tags.insertOne(tag_obj, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set unable to add to user tag')
}
else
{
console.log('tags added to user_tags')
res.send(test_tags);
db.close();
}
});
}
else
{
res.send(test_tags);
db.close();
}
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
}
});
}
}
});
}
if(req.body.op == 'set_remove') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
result['tags'].splice(result['tags'].indexOf(req.body.newtag),1);
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags removed successfully')
//collection = db.collection('user_tags');
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
res.send(result);
db.close();
}
});
}
});
}
if(req.body.op == 'get') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
//console.log('tags retrieved successfully ', result['tags'])
if(result['tags'])
res.send(result['tags'].join(","));
else
res.send("");
db.close();
}
});
}
}
});
});
app.post('/gettestprocs/:id', function(req, res){
console.log('gettestprocs body: ' + (req.body.itemId));
//var url = "mongodb://127.0.0.1:27017/og1";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({ "id" : req.body.itemId },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.post('/gettestprocsbyitemid', function(req, res){
//console.log('gettestprocs body: ' + (req.body));
var url = "mongodb://127.0.0.1:27017/onegrid_int";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
console.log(req.body)
/*if(String(req.body.grid_type) == "MANUAL"){
collection_name = "n_gve_manual_testprocs"
} else if(String(req.body.grid_type) == "OLD_MANUAL") {
collection_name = "gve_manual_testprocs"
} else if(String(req.body.grid_type) == "SURFACE") {
collection_name = "gve_surface_testprocs"
}
else if(String(req.body.grid_type) == "AUTO") {
}*/
//var tp = testplans.filter(function(x){return x.itemId == req.params.id})[0];
var collection_name = (req.body.testplan_id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({"id" : String(req.body.proc_id) },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.use('/', routes);
app.use('/testgrid', testgrid);
app.use('/hsdes_query', hsdes_query);
app.use('/find_coverage', find_coverage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000, () => console.log('Server running on port 3000!'))
module.exports = app;
another app.js in C:\projects\New Project\onegrid\web\node_modules\ejs-locals\example
var express = require('express')
, engine = require('../')
, app = express();
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
// render 'index' into 'boilerplate':
app.get('/',function(req,res,next){
res.render('index', { what: 'best', who: 'me', muppets: [ 'Kermit', 'Fozzie', 'Gonzo' ] });
});
app.get('/foo.js', function(req,res,next){
res.sendfile('foo.js');
})
app.get('/foo.css', function(req,res,next){
res.sendfile('foo.css');
})
app.listen(3000);
what am i doing wrong , i just want to run it on localhost 3000. ?
Your terminal shows you running node server.js but your file is called app.js.

Using objectid can't retrieve data from MongoDB in Node.js

When I pass objectid of 1 hospital from Postman to this program it returns only empty array. But there is one data matching that objectid. Can you help me solve this? When I try to debug the program in console, I saw the array is empty.
doctor.js:
var express = require('express');
var router = express.Router();
var app=express()
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var authentication=require('./check_authentication')
var validate = require('./validation')
var ObjectId=require('mongodb').ObjectId
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/',function(req,res)
{
if(validate.name(req.body.name) && validate.length(req.body.name) && validate.empty(req.body.name))
{
if(validate.empty(req.body.hospital_id))
{
mongo.find("hospital","_id",ObjectId(req.body.hospital_id),function(result1)
{
if(result1.length==1)
{
res.send("succcess")
}
})
}
}
})
module.exports = router;
And collection of MongoDB is:
hospital:
{
"_id" : ObjectId("5aa92df0ec6b3cc78ff88afd"),
"name" : "apollo_hospitals"
}
{
"_id" : ObjectId("5aa92df9ec6b3cc78ff88afe"),
"name" : "fortis"
}
mongoconnect.js:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function()
{
if(dbo!=null) return
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
dbo = db.db("hospital_api");
});
}
var get = function (){
return dbo;
}
exports.find=function(collections,key,value,callback)
{
get().collection(collections).find({key:value}).toArray(function(err,result)
{
// console.log(collections)
// console.log(key)
// console.log(value)
if(err) throw err;
console.log(result)
callback(result)
})
}
Here, myself i got the solution.
We have to declare ObjectID with New keyword..
Var some_variable = New ObjectID(_id)
After that we can use that id anywhere using that some_variable

Node.js Express POST call not working although GET does

I am trying to write a REST backend using Node.js, express and MongoDB but am having some issues creating PUT calls for some reason. The issue is with app.post('/contacts/add', contacts.addContacts) as it works fine if I change it to GET but when I change it to either PUT or POST I get the error Cannot GET /contacts/add Any ideas?
I am using express 4.15.3, mongodb 3.4.5 and npm 4.2.0
server.js:
var express = require('express'),
contacts = require('./routes/contacts');
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/contacts/chalkboard/:id', contacts.getChalkboardContacts);
app.get('/contacts/get/:uid', contacts.getContacts);
app.post('/contacts/add', contacts.addContacts);
app.listen(3000);
console.log('Listening on port 3000...');
contacts.js
var mongo = require('mongodb');
mongo.BSONPure = require('bson').BSONPure;
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('db', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.collection('contacts', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'contacts' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.getChalkboardContacts = function(req, res) {
var uid = req.params.uid.toString();
var date = new Date();
var timeInMs = date.getMilliseconds();
console.log(uid);
db.collection('contacts', function(err, collection) {
console.log('collection: ' + collection);
collection.find({uid: uid, lastMessage: {$gte: timeInMs}}).toArray(function(err, items) {
res.send(items);
});
});
};
exports.getContacts = function(req, res) {
var uid = req.params.uid.toString();
console.log(uid);
db.collection('contacts', function(err, collection) {
console.log('collection: ' + collection);
collection.find({uid: uid}).toArray(function(err, items) {
res.send(items);
});
});
};
exports.addContacts = function(req, res) {
console.log('working');
db.collection('contacts', function(err, collection) {
var id = "592159bc3e48764418170399";
var contact = {uid: "592159bc3e48764418173333",
keyUid: "592159bc3e48764418171444",
name: "Billy Jean",
phoneNumber: "+491721894733",
battery: "47%", longitude: "0",
latitude: "0",
city: "city",
country: "country",
place: "place",
address: "address",
lastMessage: "lastMessage",
lastUpdated: "lastUpdated"};
collection.update({'uid':id}, {$push:{'contacts':contact}}, function(err, result) {
if (err) {
console.log('Error updating contact: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(result);
}
});
});
};
I didn't spot anything immediately wrong with the code.
You might be falling into a very common pitfall when using body-parser for JSON. Your request must specify Content-Type: application/json in the request for the parser to parse it. Otherwise, it won't work.
If that doesn't do the trick, if you can share any error messages or response codes you get, it may illuminate another issue.

Node js url shortener is looping rather than redirecting

I am writing a url shortener service in Node JS using mongo to connect to mLab.
Right now the user can send a request to the service with a url to shorten, and it returns a shortened url. However, if the user then sends the shortened url as a request, the redirect does not happen. Rather, the service goes into a loop.
1) How do I see what exactly is getting grabbed from the db? (Knowing how to do this would help out in trouble-shooting)
2) And what may be the cause of the looping issue?
var express = require('express')
var app = express()
var path = require('path');
var port = process.env.PORT || 8080;
var crypto = require("crypto");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({ // this schema is used for writing to the db
url : String,
key : String
});
var urlcntrctr = new Schema( // this schema is used for reading from the db
{ key: String, url : String, _id: String },
{ collection: 'urlcntrctr'}
);
const SchemaName = mongoose.model('SchemaName', urlcntrctr); // for reading from the db
app.get('/', (req, res, next) => res.sendFile(path.join(__dirname, '/index.html')) ) ;
app.set('port', (process.env.PORT || 5000));
app.get('/new/:url(*)', function(req, res) {
var shortenme = req.params[0];
var showme = req.params[0];
console.log("User's request: " +shortenme);
var amItrue = validateURL(shortenme);
if (amItrue){
connectmongoviamongoose();
var shortenmeObj = yncryptyyn(shortenme);
shortenme = shortenmeObj.key;
writeToDb(shortenmeObj); b
closetheconnection();
var contractedurl = 'http://firstappever-olddognewtrix123.c9users.io/' + shortenme;
var responseObject = ({"Original url: ": showme, "Contracted url: ": shortenme });
res.send(responseObject);
}
else{console.log("You need to enter a url, beginning with 'http' or 'https' and ending in '.com' or '.org' or whatever!");};
})
app.get('/:tag(*)', function(req, res) {
var targetnumber = req.params.tag;
sendforRedirect(req, res);
sendforRedirect(req, res);
})
function sendforRedirect(req, res){
var target = req.params.tag;
console.log("The value of target is " + target)
; var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>#ds159988.mlab.com:59988/urlcntrctr';
mongoose.connect(mongodbUri, options);
mongoose.Promise = global.Promise;
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("OK, you are connected for the redirect. ")
var query = {
key: {
$eq: target
}
}
SchemaName.find(query, function (err, doc) {
if(err){
console.log(err);
conn.close();
};
if(doc){
res.redirect(doc.url); // rather than redirecting, it is looping *****************
conn.close();
} else {
res.send("Sorry, we don't recognize that url");
conn.close();
}
});
});
}
function writeToDb(dataObject){
mongoose.model('Document', UserSchema);
var urlFromUser = mongoose.model('Document');
var urlfromuser = new urlFromUser();
urlfromuser.url = dataObject.url;
urlfromuser.key = dataObject.key;
urlfromuser.save();
};
function validateURL(textval) { //copied from http://stackoverflow.com/questions/1303872/trying-to-validate-url-using-javascript
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*#)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
function connectmongoviamongoose(){
var mongoose = require('mongoose');
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>#ds159988.mlab.com:59988/urlcntrctr';
mongoose.createConnection(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("OK, you are connected. ")
});
}
function closetheconnection(){
var mongoose = require('mongoose');
mongoose.connection.close();
}
function yncryptyyn(incryptme){
var ulimit = 6;
var key = crypto.createHash('md5').update(incryptme).digest("base64");
key = key.slice(0,ulimit);
var obj = {
url: incryptme,
key: key
};
return obj;
}
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Better than console.log statements, you can use the package node-inspector to actually set breakpointsnin your code via chrome devtools and step through the code Much more robust process.
I would note that it is not clear to me what kind of urls you are shortening (internal to your site or external), but at present it looks like you're calling the redirect function twice, which should cause an error unto itself, and second if you are redirecting to internal urls your routes are probably going to match a lot that you don't want them to.
Finally, your code is kind of a jumble right now, which will make debugging harder no matter what you do. Try and break it out into different files based on what they do and test bits independently as much as possible.
For question 1: just put in a console.log, for example like this:
if(doc){
console.log(doc);
res.redirect(doc.url);
....
Even better put the whole functionality of the look up of the url into an own function, so you can check the working of the lookup and the working of the redirect independently.

Node.js REST with MySQL handle reconnect

I'm new to Node.js I followed tutorial from the internet for REST API with Node.js and MySQL. I can't get it to work after MySQL closes the connection or timeout occurs. Can you tell me how to modify my code to get it work:
Server.js
var express = require("express");
var mysql = require("mysql");
var bodyParser = require("body-parser");
var rest = require("./REST.js");
var app = express();
function REST(){
var self = this;
self.connectMysql();
};
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool({
connectionLimit : 50,
host : 'localhost',
user : 'root',
password : '',
database : 'quiz',
debug : false,
multipleStatements: true
});
pool.getConnection(function(err,connection){
if(err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
}
REST.prototype.configureExpress = function(connection) {
var self = this;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.use('/', router);
var rest_router = new rest(router,connection);
self.startServer();
}
REST.prototype.startServer = function() {
app.listen(3000,function(){
console.log("All right ! I am alive at Port 3000.");
});
}
REST.prototype.stop = function(err) {
console.log("ISSUE WITH MYSQL n" + err);
process.exit(1);
}
new REST();
REST.js
var mysql = require("mysql");
function REST_ROUTER(router,connection) {
var self = this;
self.handleRoutes(router,connection);
}
REST_ROUTER.prototype.handleRoutes= function(router,connection) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
});
router.get("/quiz/cars",function(req,res){
var options = {sql: 'SELECT quiz.quiz_id, quiz_image, quiz_type, choice_id, choice, is_right_choice FROM quiz JOIN quiz_choices ON quiz.quiz_id = quiz_choices.quiz_id WHERE quiz_type="cars";', nestTables: false};
connection.query(options,function(err,rows){
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
res.json(rows);
}
});
});
}
module.exports = REST_ROUTER;
I have the same issue a and think this may be the solution. I made the following changes to my code:
Pass the connection pool rather than the connection to self.configureExpress() like so...
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool(db_config);
self.configureExpress(pool);
};
and
REST.prototype.configureExpress = function(pool) {
....
var rest_router = new rest(router,pool,md5);
....
}
REST.js
var mysql = require("mysql");
function REST_ROUTER(router,pool) {
var self = this;
self.handleRoutes(router,pool);
}
REST_ROUTER.prototype.handleRoutes= function(router,pool) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
});
router.get("/quiz/cars",function(req,res){
var options = {sql: 'SELECT quiz.quiz_id, quiz_image, quiz_type, choice_id, choice, is_right_choice FROM quiz JOIN quiz_choices ON quiz.quiz_id = quiz_choices.quiz_id WHERE quiz_type="cars";', nestTables: false};
pool.getConnection(function(err, connection) {
connection.query(options,function(err,rows){
connection.release();
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
res.json(rows);
}
});
});
});
}
module.exports = REST_ROUTER;
Don't forget to call connection.release(); after you've finished using the connection so that it can be added back to the connection pool.

Categories

Resources