Error trying to connect to MongoHQ database from node.js app - node.js

Can't seems to understand what is the problem.
var MongoClient = require('mongodb').MongoClient;
console.log('Trying to connect with', settings );
MongoClient.connect( settings.mongourl, settings.options, function(err, db) {
if(!err) {
console.log("We are connected");
callback( true, db );
}
else {
console.log("Connection failed", err );
callback( false, null );
}
});
In result I get (changed some parts to xxxx):
Trying to connect with { mongourl: 'mongodb://xxxx:xxxx#xxxx.mongohq.com:xxxx/testdb', options: {auto_reconnect: true}}
Connection failed [Error: failed to connect to [xxxx.mongohq.com:xxxx]]
I have doublechecked the url string for connection, everything is ok, tried to create another user just for testing - still getting errors. The worst part is that the description in error doesn't give any hint what cause the problem.
Just in case, my package.json dependancy part:
"dependencies": {
"fetch": "~0.3.6",
"mongodb": "~1.4.3",
"connect-mongo": "~0.4.1",
"amqp": "~0.2.0",
"express": "~4.1.1",
"express-session": "~1.0.4",
"connect": "~2.15.0"
}

Use the same connection string and try to connect using mongo client.
mongo --host "xxxx.mongohq.com" --port "XXXX" --username "" -p ""
See if you can connect thru the shell or not.
For more info look here: http://docs.mongodb.org/v2.2/reference/mongo/#bin.mongo

Related

How to connect Redshift database using Node JS

I am not able to connect to the redshift database using Node. I am using Node JS version 14.15.1.
Is there any issue related to this version?
The following code, I have tried in my local machine,
redshift.js file
var Redshift = require('node-redshift');
var client = {
user: 'user',
database: 'db',
password: 'password',
port: port,
host: 'hostname',
};
var redshiftClient = new Redshift(client, {rawConnection:true});
module.exports = redshiftClient;
The following is the code to get the values from database,
index.js file
var redshiftClient = require('./redshift.js');
console.log('Before Connection');
redshiftClient.connect(function(err){
console.log('After Connection');
if(err) throw err;
else{
redshiftClient.query('SELECT * FROM "customer"', {raw: true}, function(err, data){
if(err) throw err;
else{
console.log(data);
redshiftClient.close();
}
});
}
});
If I run this code not getting the error and even this line is also not executed console.log('After Connection');
The package seems a bit abandoned as here's an open issue with exact issue
To solve that you need to apply this solution manually
go to node_modules/node-redshift and replace
"dependencies": {
"commander": "^2.9.0",
"migrate": "^0.2.2",
"pg": "^6.1.2",
"sql-bricks": "^1.2.3"
},
in package.json to
"dependencies": {
"commander": "^2.9.0",
"migrate": "^0.2.2",
"pg": "^8.1.5",
"sql-bricks": "^1.2.3"
},
run npm install in this directory in order to update this package. After that your code will work
This library is not very active, as mentioned above there's an open issue in github from 2020.
It's better to use pg-promise
Attaching a script link here.
https://www.javaniceday.com/post/how-to-connect-to-a-redshift-database-from-node-js

MSSQL Connection login failed for user in node js

i am trying to connect mssql database but i couldnt achieve that.
When i connect mssql on Microsoft SQL Server Management Studio 18;
https://i.stack.imgur.com/6xdI0.png -- Because of Windows Authentication, i have no password. And there is a username field passive as default, also node js doesnt accept default user name. Why? and what i am doing wrong? When i try to execute js file; https://i.stack.imgur.com/Ty0zA.png -- gives an user name error in cmd db.js file;
var sql = require('mssql');
// config for your database
var config = {
user: 'DESKTOP-S9H932R\\CUNEYT',
password: '',
server: 'localhost',
database: 'cuneyt'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from borsa', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
package.json file;
{
"name": "mssql_test",
"version": "1.0.0",
"description": "",
"main": "db.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mssql": "^6.3.1"
}
}
OP solved but for anyone having trouble my issue was that I was connecting to a local DB within a domain. I had to add the option to my config object to be like
config:{
user:'xxxx',
password:'xxxx',
server:'servername',
database:'yourdb'
domain:'yourdomainname'}

loopback nodejs server not starting

I have project with nodejs loopback 3.x version and I am recently turned dev in nodejs. I have written the models, server aspects (server.js, server/root.js) etc. Following are the dependencies:
"dependencies" : {
"#types/async": "2.0.40",
"#types/lodash": "4.14.139",
"#types/loopback": "3.1.3",
"#types/loopback-boot": "2.23.0",
"loopback-connector-rest": "3.0.0",
"loopback-model-binder": "1.4.0",
"#types/multiparty": "0.0.31",
"rimraf": "2.6.1",
"sinon": "3.2.1",
"ts-node": "3.3.0",
"typescript": "2.8.3",
"gulp-sequence": "0.4.6",
"gulp-symlink": "2.1.4",
"gulp-typescript": "4.0.1",
"request": "2.81.0",
"shelljs": "0.8.1",
"yargs": "11.0.0",
"os-locale": "3.1.0",
"loopback-connector": "4.4.0",
"strong-globalize": "2.10.0",
"strong-remoting": "3.14.0"
}
This is my code snippet in server.ts:
const app: any = loopback();
boot(app, __dirname, (err) => {
if (err) throw err;
});
app.start = () => {
return app.listen(() => {
const BASE_URL = app.get('url').replace(/\/$/, '');
const explorer = app.get('loopback-component-explorer');
if (explorer) {
Logger.info(`Browse your REST API at ${BASE_URL}${explorer.mountPath}`);
}
});
};
Following are the steps for installing and starting app:
npm install
npm run build
npm run start
But the application is not starting, no errors but returns at command prompt. I enabled the verbose output for the npm run start -verbose command and I found following:
loopback:datasource Module ./connectors/rest not found, will try another candidate. +10ms
loopback:datasource Initializing connector RequestBuilder +561ms
loopback:datasource Connector is initialized for dataSource rest +7ms
loopback:datasource DataSource rest is now connected to undefined +1ms
lifecycle port-app#2.0.0~start: unsafe-perm in lifecycle true
Please let me know about any pointers regarding the above issue.
it was a silly miss from my part. Once you create the app and then in boot process you need to start the application.
boot(app, __dirname, (err) => {
if (err) throw err;
app.start(); // <-- Fix
});

Cloud Foundry MongoDB Error ECONNREFUSED

I would like to deploy a Node.JS app on Cloud Foundry.
I follow the following steps:
Add the engines part in the package.json
{
"name": "vsapc",
"version": "1.0.0",
"description": "Application Name",
"main": "server/app.js",
"scripts": {
"start": "node server/app.js",
"backup": "node backup.js",
"restore": "node restore.js",
"seed": "node server/seed/Seed.js",
"postinstall": "node install.js"
},
"directories": {
"test": "test"
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.15.2",
"cfenv": "^1.0.3",
"express": "^4.14.0",
"jsonwebtoken": "^7.1.9",
"mongodb": "^2.2.5",
"mongoose": "^4.6.3",
"mongoose-seed": "^0.3.1",
"morgan": "^1.7.0",
"promise": "^7.1.1",
"prompt": "^1.0.0",
"winston": "^2.2.0",
"winston-daily-rotate-file": "^1.4.0"
},
"engines": {
"node": "6.11.*",
"npm": "5.*"
},
"author": "",
"license": "ISC"
}
I create the manifest.yml
---
applications:
- name: Policy_Studio
memory: 2048MB
env:
NODE_ENV: production
I used the following to connect in install.js:
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
let mongoUrl = '';
mongoUrl = vcapServices.mongodb[0].credentials.uri;
mongoose.connect(mongoUrl,{useMongoClient: true}, function (err){
if (err) {
console.log("Database connection responded with: " + err.message);
console.log("Is your server.config.json up to date?");
process.exit(1);
return
}
console.log("Connected to database.");
and the following in app.js:
Server.prototype.connectDatabase = function (url) {
mongoose.Promise = Promise;
const vcapServices = JSON.parse(process.env.VCAP_SERVICES);
let mongoUrl = '';
mongoUrl = vcapServices.mongodb[0].credentials.uri;
mongoose.connect(mongoUrl,{useMongoClient: true});
mongoose.connection.on("error", function (err) {
log.error(err)
});
mongoose.connection.once("openUri", function () {
log.info("Connected to DB")
})
};
connect by command line to SCAPP and push the app with cf push
As i don't have the MongoDB on the cloud i have an error
I build a MOngoDB service on the cloud and bind directly the app through the web GUI
On the gui i click restage button for my app
I have the error
Database connection responded with: failed to connect to server
[2xtorvw9ys7tg9pc.service.consul:49642] on first connect [MongoError:
connect ECONNREFUSED 10.98.250.54:49642]
I add the service mongoDB in my manifest and cf push my application
Still the same error as in point 9
I tried to change the connection in install.js
Thank you for your help
While your parsing of VCAP_SERVICES appears to work (you get a URL containing a hostname & port), i highly recommend to leverage one of the existing libraries for it for further projects:
https://www.npmjs.com/package/cfenv
Still, please that the parsing of your mongo credentials is properly working (cf e ${app_name}, look for VCAP_SERVICES, manually compare)
If you want to test your service with independent code, here is a sample app i quickly threw together to test all mongodb services bound to it:
package.json:
{
"name": "mongo-tester",
"version": "1.0.0",
"description": "tests all mongodbs via VCAP_SERVICES",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Michael Erne",
"license": "MIT",
"dependencies": {
"async": "^2.5.0",
"cfenv": "^1.0.4",
"lodash": "^4.17.4",
"mongodb": "^2.2.31"
}
}
server.js:
var cfenv = require('cfenv'),
_ = require('lodash'),
http = require('http'),
async = require('async'),
MongoClient = require('mongodb').MongoClient
var appEnv = cfenv.getAppEnv();
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Return something for CF Health Check\n');
}).listen(appEnv.port);
var services = _.values(appEnv.getServices());
var mongodbs = _.filter(services, { label: 'mongodb' });
async.eachLimit(mongodbs, 1, function (m, callback) {
MongoClient.connect(m.credentials.database_uri, function (err, db) {
if (err) {
return callback(err);
}
db.collection("debug").insertOne({"test": true}, function(err, res) {
if (err) return callback(err);
console.log("document inserted successfully into " + m.credentials.database_uri);
db.close();
return callback(null);
});
});
}, function (err) {
if (err) {
console.log(err.stack || err);
console.log('---> mongodb connection failed <---');
return;
}
console.log('---> connection to all BOUND mongodb successful <---');
});
It should print something like the following in its logs if it can connect to any of the bound mongodb services:
document inserted successfully into mongodb://xxx:yyy#zzz.service.consul:1337/databaseName
---> connection to all BOUND mongodb successful <---
If this fails with similar errors, the service instance seems broken (wrong url/port being reported). I would just recreate the service instance in that case and try again.
Finally we have found the problem. The cloud foundry is not allowing to access the MongoDB service during the postinstall phase. So we changed it to prestart and it worked.
Thank you for your help

I am unable to push my Node.js with Mongodb backend project on Bluemix. Instance creation is failed

The following the log dump from my cf push :
2014-09-09T15:47:35.92+0530 [App/0] ERR 2014-09-09T15:47:35.97+0530
[DEA] OUT Instance (index 0) failed to start accepting connections
2014-09-09T15:47:55.71+0530 [DEA] OUT Starting app instance (index
0) with guid 20dba222-e0e6-453c-96a9-429940bc7002
2014-09-09T15:47:57.59+0530 [API] OUT App instance exited with
guid 20dba222-e0e6-453c-96a9-429940bc7002 payload:
{"cc_partition"=>"default",
"droplet"=>"20dba222-e0e6-453c-96a9-429940bc7002",
"version"=>"832505e6-a95d-4696-910e-a8d4a74a7005",
"instance"=>"4ff487a75a674aa79b234cc1bd8f9a3d", "index"=>0,
"reason"=>"CRASHED", "exit_status"=>0, "exit_description"=>"app
instance exited", "crash_timestamp"=>1410257878} 2014-09-09T
This is how my manifest.yml file looks like :
applications:
- name: nodetestSDB
memory: 128M
command: node app.js
services:
- mongodbnode
This is how my package.json file looks like :
{
"name": "nodetest2",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~4.8.6",
"body-parser": "~1.6.6",
"cookie-parser": "~1.3.2",
"morgan": "~1.2.3",
"serve-favicon": "~2.0.1",
"debug": "~1.0.4",
"jade": "~1.5.0",
"mongodb": "*",
"monk": "*"
}
}
The environment variable in app.js :
if (process.env.VCAP_SERVICES) {
var env = JSON.parse(process.env.VCAP_SERVICES);
if (env['mongodb-2.2']) {
var mongo = env['mongodb-2.2'][0]['credentials'];
}
var db = monk(mongo.url);
}
Please take a look at my posts on using MongoDB with Bluemix in my blog. You can also check the code in GitHub abd Devops. Most likely you are not parsing the VCAP_SERVICES right. I have used both Node.js & NodeExpress
http://gigadom.wordpress.com/2014/07/27/a-bluemix-recipe-with-mongodb-and-node-js/
http://gigadom.wordpress.com/2014/08/04/elements-of-crud-with-nodeexpress-and-mongodb-using-enide-studio/
http://gigadom.wordpress.com/2014/08/07/spicing-up-a-ibm-bluemix-cloud-app-with-mongodb-and-nodeexpress/
Regards
Ganesh
It looks like you have two different start commands for you app.
In manifest.yml you are using "node app.js" and in your package.json you are using "node ./bin/www".
Try having those two files match and that should help. Let me know if it doesn't work.
app.js:
console.log('VCAP SERVICES: ' + JSON.stringify(process.env.VCAP_SERVICES, null, 4));
var mongoUrl;
if(process.env.VCAP_SERVICES) {
var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
for (var svcName in vcapServices) {
if (svcName.match(/^mongo.*/)) {
mongoUrl = vcapServices[svcName][0].credentials.uri;
mongoUrl = mongoUrl || vcapServices[svcName][0].credentials.url;
break;
}
}
}
else
{
mongoUrl = "localhost:27017/SScheduler";
}
console.log('Mongo URL: ' + mongoUrl);
// Database
var mongo = require('mongoskin');
var db = mongo.db(mongoUrl, {native_parser:true}); -->through bluemix
//var db = mongo.db("mongodb://localhost:27017/nodetest2", {native_parser:true}); -->through local setup
i tried like this and it worked for both local and through bluemix

Resources