Could not connect with MongoLab database URl using node.js and Heroku - node.js

I could not connect to MongoDB which is present in MongoLAB . I have one MEAN app and I have deployed in heroku. When I am trying to connect with database but could not. The logs are given below.
Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect...
2017-07-31T11:46:48.243603+00:00 app[web.1]: at module.exports (/app/node_modules/mongodb/lib/url_parser.js:59:13)
2017-07-31T11:46:48.243605+00:00 app[web.1]: at Function.MongoClient.connect (/app/node_modules/mongodb/lib/mongo_client.js:113:3)
2017-07-31T11:46:48.243604+00:00 app[web.1]: at connect (/app/node_modules/mongodb/lib/mongo_client.js:289:16)
2017-07-31T11:46:48.243606+00:00 app[web.1]: at run (/app/node_modules/thunky/index.js:13:3)
2017-07-31T11:46:48.243606+00:00 app[web.1]: at /app/node_modules/mongojs/lib/database.js:29:15
2017-07-31T11:46:48.243607+00:00 app[web.1]: at Collection._getConnection (/app/node_modules/thunky/index.js:27:3)
2017-07-31T11:46:48.243608+00:00 app[web.1]: at Collection._getCollection (/app/node_modules/mongojs/lib/collection.js:17:10)
2017-07-31T11:46:48.243609+00:00 app[web.1]: at getCursor (/app/node_modules/mongojs/lib/collection.js:32:10)
2017-07-31T11:46:48.243610+00:00 app[web.1]: at run (/app/node_modules/thunky/index.js:13:3)
2017-07-31T11:46:48.243609+00:00 app[web.1]: at /app/node_modules/mongojs/lib/cursor.js:12:5
2017-07-31T11:46:48.244240+00:00 app[web.1]: [0mPOST /login [31m500 [0m30.134 ms - 22[0m
Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect...
My code is below:
var mongoJs=require('mongojs');
var CryptoJS = require("crypto-js");
var database='FGDP';
var collections=['f_users'];
var MONGOLAB_URI="mongodb://username:password#ds127153.mlab.com:27153/fgdp";
var db=mongoJs(MONGOLAB_URI, collections);
var ses;
exports.userlogin=function(req,res){
var username=req.body.user_name;
var password=req.body.user_pass;
// console.log('pass'+typeof(password));
//var ciphertext = CryptoJS.AES.encrypt(password, 'lexelPass');
//var pass=ciphertext.toString();
db.f_users.findOne({'login_name':username},function(err,docs){
console.log('err',err);
if(!err){
if(docs){
var pass=docs.password;
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'lexelPass');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
if(plaintext==password){
req.session.email=docs.email;
req.session.name=docs.name;
req.session.login_name=docs.login_name;
req.session.status=docs.status;
req.session.user_type=docs.user_type;
res.send(docs);
}else{
res.send("Login failed");
}
}
}
if(err){
res.send("Login failed");
}
})
}
That database and collection is present in mongoLAB. I need to connect it through mongojs. Actally I have a login App and I could not login.

You should do like
var db = mongoJs(MONGOLAB_URI);
db.on('connect', function () {
console.log('database connected')
});

Related

Unable to connect to Microsoft SQL Server using Node.js,mssql and express

I am trying to learn Node.js and created a simple project to query the local database. But I get failed to look up an instance error message.
I have checked that the SQL Server services running in services.msc
I have verified TCP/IP is enabled
I have tried with the username and password and without it as well. I connect to localdb in SQL Server Management Studio as (localdb)\v11.0 and below is the screenshot of the properties
What am I doing incorrectly? What should be actual username and password? What should be the servername?
const sql = require('mssql');
// config for your database
const config = {
user: 'mywindows username',
password: 'my windows password',
server: '(localdb)\\v11.0',
database: 'test',
options: {
encrypt: true
}
};
console.log('starting sql');
var connection = new sql.connect(config, function(err) {
console.log(err);
var request = new sql.Request(connection);
request.query('select * from employees', function(err, recordset) {
if(err) // ... error checks
console.log('Database connection error');
console.dir("User Data: "+recordset);
});
});
sql.close();
console.log('ending sql');
});
app.listen(3002, () => {
console.log('Listening on port 3002');})
Below is the error message
{ ConnectionError: Failed to lookup instance on (localdb) -
getaddrinfo ENOTFOUND (localdb)
at Connection.tedious.once.err (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:285:13)
at Connection.emit (events.js:197:13)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:16)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17) code: 'EINSTLOOKUP', originalError: { ConnectionError: Failed to
lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)
at ConnectionError (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\errors.js:13:12)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:32)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17)
message:
'Failed to lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)',
code: 'EINSTLOOKUP' }, name: 'ConnectionError' } Database connection error
After struggling for hours on this one finally found the answer here SQL to Node connection
It seems i have to add msnodesqlv8 package and use add the driver syntax to the config.
app.get('/test', (req, res) => {
const sql = require('mssql/msnodesqlv8');
// config for your database
const config = {
database: 'test',
server: '(localdb)\\v11.0',
driver: 'msnodesqlv8',
options : {
trustedConnection : true
}
};
console.log('starting sql');
const pool = new sql.ConnectionPool(config);
pool.connect().then(() => {
//simple query
pool.request().query('select * from employees', (err, result) => {
if(err) res.send(err)
else{
return res.json({
data : result.recordset
})
}
})
sql.close();
})
console.log('ending sql');
});
you will need msnodesqlv8 driver, which you have to paste it in require as
var sql = require('mssql/msnodesqlv8'),
as well as you will have to include it in driver section in config object.
var config = {
user:"*****",
password:"*****",
database:"*****",
driver: 'msnodesqlv8',
server:"*****",
options: {
trustedConnection : true
}
}

Connect Node.js BOT to MS Azure SQL database

I have a working MS Teams bot written in Node.js. The bot asks a series of questions and currently displays the responses at the end by accessing the session variables. All well and good.
Now I am attempting to store the session variables in a MS Azure SQL DB. The DB is correctly set up in Azure as I can access and write data to it in SSMS. But I believe I am probably connecting incorrectly to the DB in my bot code. The bot code I am using is pulled from:
connecting to SQL using Node.js
That code makes sense to me. But how do I use that code in my bot? Here is what I have attempted thus far...
Currently I am using the local memory MemoryBotStorage() and setting to that.
var inMemoryStorage = new builder.MemoryBotStorage();
.set('storage', inMemoryStorage)
In another Microsoft article dealing with the Azure Cosmos DB it states "4.Specify that you want to use your custom database instead of the in-memory storage." So from this I deduce that I hafta add my instantiated sql db to the .set('storage', DB Goes Here) but my attempts have failed and I am not sure if I am even correct?
So my question is how do I correctly access the Azure sql server DB form my bot code - and is the link I provided even the correct way?
Thank you
Note - This code sample worked for me - I was able to connect and query my Azure DB - but it is only DB code and does not take into consideration bot code.
EDIT - Code:
const builder = require('botbuilder');
const builderTeams = require('botbuilder-teams');
const restify = require('restify');
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID,
appPassword: "My App PW",
}
);
var inMemoryStorage = new builder.MemoryBotStorage();
const bot = new builder.UniversalBot(connector, [
function (session) {
session.send("Welcome.");
builder.Prompts.text(session, "Question1?");
},
function (session, results) {
session.dialogData.question1 = results.response;
builder.Prompts.text(session, "Question2?");
},
function (session, results) {
session.dialogData.Question2 = results.response;
builder.Prompts.text(session, "Question3?");
},
function (session, results) {
session.dialogData.Question3 = results.response;
// Begin DB
var Connection = require('tedious').Connection;
var config = {
userName: 'myusername',
password: 'mypw',
server: 'myserver.database.windows.net',
// If you are on Azure SQL Database, you need these next options.
options: { encrypt: true, database: 'mydb' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement1();
});
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;
function executeStatement1() {
request = new Request("INSERT my (Username, Question1, Question2, Question3, StatusDate) VALUES (#Username, #Question1, #Question2, #Question3, CURRENT_TIMESTAMP);", function (err) {
if (err) {
console.log(err);
}
});
request.addParameter('Username', TYPES.NVarChar, session.userData.userName);
request.addParameter('Question1', TYPES.NVarChar, session.dialogData.Question1);
request.addParameter('Question2', TYPES.NVarChar, session.dialogData.Question2);
request.addParameter('Question3', TYPES.NVarChar, session.dialogData.Question3);
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log("ID of inserted item is " + column.value);
}
});
});
connection.execSql(request);
// End DB
// Process request and display details
session.endDialog();
}
]).set('storage', inMemoryStorage)
const server = restify.createServer();
server.post('api/messages', connector.listen());
server.listen(portnumber)
Error when running with npm start:
npm start
> simplebot#1.0.0 start C:\Developer\dailyStatus
> node index.js
C:\Developer\dailyStatus\index.js:81
]).set('storage', inMemoryStorage)
^
SyntaxError: Unexpected token ]
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! simplebot#1.0.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the simplebot#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely...
npm ERR! A complete log of this run can be found in:
npm ERR! C: etc.
FINAL
I was able to able to get this working with this tutorial. Thanks also to Marc LeFleur.
You have several typos. For example, you're missing the closing " on appId:
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID",
appPassword: "My App PW",
}
);
You also can't declare the function executeStatement1() {...} function within the your IDialogWaterfallStep function. This needs to live outside the constructor and called from the IDialogWaterfallStep.

net.Stream is not a constructor - Node Postgres

I'm trying to connect a Node.js app with a PostgreSQL server. It seems that no matter what I use, I end up with the same error:
bundle.js:16177 ERROR: TypeError: net.Stream is not a constructor
at new Connection (bundle.js:10133)
at new Client (bundle.js:9704)
at Object.create (bundle.js:11308)
at Pool._createResource (bundle.js:510)
at Pool.dispense [as _dispense] (bundle.js:498)
at Pool.acquire (bundle.js:573)
at Pool.pool.connect (bundle.js:11359)
at PG.connect (bundle.js:10876)
at bundle.js:1642
At first I was declaring a new pg.Client() like the example in the documentation here, but got the above error discovered that might be a bad idea according to this stack overflow post.
I tried using pg.connect():
var pg = require('pg'); //postgresql dependency
var connectionString = "postgres://postgres:thisissuchagoodpassword#PostgreSQL/localhost:5432/Milestone1DB"
console.log("Initiating...");
//var connectionString = "postgres://postgres:thisissuchagoodpassword#PostgreSQL9.6/localhost:5432/Milestone1DB";
//var client = new pg.Client();
//connect to the database
console.log("Attempting to connect to the database");
pg.connect(function (err, client, done)
{
if(err)
{
console.log("Error connecting to the database.");
throw err;
}
client.query("SELECT DISTINCT state FROM business ORDER BY state", function (err, result)
{
if(err)
{
console.log("Query resulted in an error.");
throw err;
}
console.log(result.rows[0]);
client.end(function (err)
{
if(err)
{
console.log("Error disconnecting from the databse.");
throw err;
}
});
});
});
Here is the pg-promise code that I tried:
var pgp = require('pg-promise');
var cn = {
host: 'localhost', // server name or IP address;
port: 5432,
database: 'Milestone1DB',
user: 'postgres',
password: 'thisissuchagoodpassword'
};
var db = pgp(cn); // database instance;
db.any("select distict state from business order by state;")
.then(data => {
console.log("DATA:", data);
})
.catch(error => {
console.log("ERROR:", error);
});
I must be missing something, but I don't know where to look. Thank you to anyone who can help me figure out what this error means.
Make sure you are not crossing a context boundary that is corrupting the net prototype chain and stripping away methods like Stream(). I ran into a similar unhandled Promise exception w Node 7.5 and pg-live-select. However it was intermittent because of the way the net reference was being passed around. I ended up using V8 inspector and putting a 'debugger' statement directly above line 13 in connection.js to catch the corruption.
node_modules/lib/connection.js:13
this.stream = config.stream || new net.Stream();
^
TypeError: net.Stream is not a constructor
at new Connection (node_modules/pg-live-select/node_modules/pg/lib/connection.js:13:34)
at new Client (node_modules/pg-live-select/node_modules/pg/lib/client.js:26:37)
at Object.create (node_modules/pg-live-select/node_modules/pg/lib/pool.js:27:24)
at Pool._createResource (node_modules/generic-pool/lib/generic-pool.js:325:17)
at Pool.dispense [as _dispense] (node_modules/generic-pool/lib/generic-pool.js:313:12)
at Pool.acquire (node_modules/generic-pool/lib/generic-pool.js:388:8)
at Pool.pool.connect (node_modules/pg-live-select/node_modules/pg/lib/pool.js:78:14)
at PG.connect (node_modules/pg-live-select/node_modules/pg/lib/index.js:49:8)
at LivePg._updateQuery (node_modules/pg-live-select/index.js:295:6)
at node_modules/pg-live-select/index.js:160:14
at Array.forEach (native)
at Timeout.performNextUpdate [as _onTimeout] (node_modules/pg-live-select/index.js:159:23)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)

Heroku web process timeout while running a daemon server of node.js backed with mongodb

I have running a daemon server to post the social network feeds on scheduled time.
Currently, I have issue while running daemon server which is written in node.js and express framework backed with mongodb.
Please see the following error which I got from heroku logs command.
←[36m2014-11-05T12:07:26.934753+00:00 app[web.1]:←[0m Daemon worker process is online.
←[36m2014-11-05T12:07:28.147952+00:00 app[web.1]:←[0m Starting daemon server
←[36m2014-11-05T12:07:28.230621+00:00 app[web.1]:←[0m APN agent connected.
←[36m2014-11-05T12:07:27.730718+00:00 app[web.1]:←[0m Successfully connected to MongoDB
←[36m2014-11-05T12:08:27.375215+00:00 heroku[web.1]:←[0m State changed from starting to crashed
←[36m2014-11-05T12:07:23.455341+00:00 heroku[web.1]:←[0m State changed from crashed to starting
←[36m2014-11-05T12:08:26.523383+00:00 heroku[web.1]:←[0m Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
←[36m2014-11-05T12:08:26.523870+00:00 heroku[web.1]:←[0m Stopping process with SIGKILL
←[36m2014-11-05T12:08:27.369727+00:00 heroku[web.1]:←[0m Process exited with status 137
As you can see that daemon server script run successfully but after that Heroku log showing me the boot timeout error.
var cluster = require('cluster')
if(cluster.isMaster){
cluster.fork()
cluster.on('online', function(worker){
console.log('Daemon worker process is online.')
})
cluster.on('exit', function(worker){
console.log('Daemon worker process has died. Booting another.')
cluster.fork()
})
} else {
var mongoose = require('mongoose')
var mongoDbURI
if(process.argv.indexOf('localdb') != -1){
mongoDbURI = 'mongodb://[IP]/[appname]'
} else {
//mongoDbURI = 'mongodb://[db url]'
mongoDbURI = '[db url]'
}
var mongoDbOptions = {}
if(process.env.MONGODB_URI)
mongoDbURI = process.env.MONGODB_URI
if(process.env.MONGODB_OPTIONS)
mongoDbOptions = JSON.stringify(process.env.MONGODB_OPTIONS)
var Agenda = require('agenda')
var agenda = new Agenda()
.database(mongoDbURI, 'daemonTasks')
.processEvery('1 minute')
//On termination of daemon, gracefully shut down jobs
function gracefulShutdown() {
agenda.stop(function() {
console.log("Shutting down daemon server")
process.exit(0)
})
}
process.on('SIGTERM', gracefulShutdown)
process.on('SIGINT' , gracefulShutdown)
var fs = require('fs-extra')
mongoose.connect(mongoDbURI, mongoDbOptions)
var db = mongoose.connection
db.on('error', function(err){
//If the database can not be connected to, die
console.error("Error connecting to MongoDB\r\n", err)
process.exit()
})
db.once('open', function(){
//Connection successful
console.log("Successfully connected to MongoDB")
//Begin loading our schema
require('./Models/models')(mongoose, function(err, models){
//Set up the agenda piece
var Agenda = require('agenda')
models.Agenda = new Agenda()
.database(mongoDbURI, 'daemonTasks')
// Connect to the Apple Push Notification Service
models.APNAgent = require('./Modules/apnAgent')(models)
if(err){
console.log("Error loading models\r\n", err)
process.exit()
}
var async = require('async')
fs.readdir('./Daemons/', function(err, files){
if(err){
console.log(err)
cb(err)
} else {
async.each(files, function(file, cb){
fs.lstat('./Daemons/' + file, function(err, stat){
if(err){
cb(err)
} else {
if(stat.isFile()){
var daemon = require('./Daemons/' + file)(models)
agenda.define(daemon.name, daemon.options, daemon.job)
cb(null)
} else {
cb(err)
}
}
})
}, function(err){
if(err){
console.log("Error starting daemon server: ", err)
return
}
console.log("Starting daemon server")
agenda.start()
})
}
})
})
})
}
I have researched on web and found some solutions which suggest for this problem is to increase the web process time but did not find the place on Heroku where I can set this value.

Unable to connect to MongoDB using node.js

I installed MongoDB in my machine and I'm able to start mongod and connect to the db using the mongo command. I even imported some data in the mycol collection of the mydb db:
$ sudo start mongodb
mongodb start/running, process 31008
$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use mydb
switched to db mydb
> db.mycol.count();
5730
> ^C
bye
But now if I want to access the db via node.js it doesn't work anymore, I get a TypeError.
I try this code (UPDATED):
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mydb', function(err, db) {
if(err) throw err;
console.log("connected!");
});
This is based on the npm module mongodb, I also tried mongoose and mongojs, each time with the same result. As soon as I want to connect to the database, I get a TypeError.
$ node mngclient.js
Failed to load c++ bson extension, using pure JS version
events.js:172
throw TypeError('type must be a string');
^
TypeError: type must be a string
at TypeError (<anonymous>)
at EventEmitter.once (events.js:172:11)
at Server.Base._registerHandler (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/base.js:387:23)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/server.js:410:12)
at EventEmitter.emit (events.js:91:17)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:111:15)
at EventEmitter.emit (events.js:97:17)
at Socket.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection.js:297:10)
at Socket.EventEmitter.emit (events.js:116:20)
at Object.afterConnect [as oncomplete] (net.js:848:10)
UPDATE:
The version of the mongodb npm package is 1.3.23
npm outdated shows no output, so I guess my packages are up-to-date
Using mongoose with the following very simple code brings up the exact same error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
UPDATE II:
I still couldn't resolve this issue on my machine
I setup the whole project in a virtual machine using vagrant. It works like a charm.
You should read the document , your trying to start a server(I'm not sure why?) here is an example on connecting to the mongo database you already have running :
MongoClient.connect('mongodb://localhost:21017/myDb', function(err, db) {
"use strict";
if(err) throw err;
...//your code
});
Step 1: npm install mongodb
Step 2: create a file, name it suppose : app.js
Paste the following content into the file:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'myDB';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
Step 3 : node app.js
Step 4: run mongod and mongo, check updated db list using show dbs
Database will be created and a collection named 'documents' will be added over there.

Resources