Simpler way to connect to a DB with NodeJS - node.js

Connecting to any DB with Java is very simple - I just need the appropriate JAR in the classpath. Alternatively, steps involved in installing any of the (example) Oracle drivers for NodeJS are very complicated (you need the windows sdk, visual studio, python 2.7, a whole bunch of environment variables). This leads me to think I'm missing something. Is there a simpler way to connect?

1. Connecting a SQL Database:
There are node modules which will help you connect to DB. Lets consider mysql as of now:
npm install mysql
Consider the mysql module. Please have a look at the documentation. From the Docs itself:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
2.Connecting a NoSQL Database:
Node.js really works well with NoSQL databases. If you are considering MongoDB,
npm install mongodb
Then try:
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
db.collection('test', function(err, collection) {});
db.collection('test', {w:1}, function(err, collection) {});
db.createCollection('test', function(err, collection) {});
db.createCollection('test', {w:1}, function(err, collection) {});
});

Related

db.createCollection is not a function

I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.
My mongo instance is running within docker and the ports have been opened up to my local.
TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Copied from w3schools...
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
No error is returned through the run, and no methods are exposed on the db object.
any ideas?
According to the changelog for Mongodb 3.0 you now get a client object containing the database object instead:
So you need the db object that points to the database you want to use, in your case mydb. Try this:
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) { //here db is the client obj
if (err) throw err;
var dbase = db.db("mydb"); //here
dbase.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close(); //close method has also been moved to client obj
});
});
You're not the one facing this issue. Seems that 3.0 mongo driver has a bug or these are just breaking backwards compatibility changes. Take a look here:
db.collection is not a function when using MongoClient v3.0
To use DB name in the URL, you need to uninstall MongoDB, change to "mongodb": "^2.2.33" in dependencies and do npm install to install the new version.
Or you can install specific version with command npm install mongodb#2.2.33 --save
I was getting the error while running createCollection() from the command line Mongo shell tool mongosh.
TypeError: db.createCollection is not a function
In my case, I could not get create collection to work, so I resorted to just inserting a document into the collection which I wanted to create. By default, Mongo will create a collection by that name on the fly, assuming you have the permissions to do so. This is not an ideal solution, but it allowed me to proceed at least.

Does mongodb require connection on each operation

So i am very new to mongodb and i wish to use it in my application. Now i HATE redundant code but reading up on how to use mongodb with node.js it seems that there is a pattern where you always have to connect before making any CRUD operation.
Example from the offical documentation:
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
My question is. is it possible to make a middleware that keeps the connection open so you only has to call insertDocument (in the above example) ?
Yea of course, just keep the db variable around until you don't need it any longer - then call close()
var mdb;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
mdb = db;
insertDocument(mdb, function() {
// ...
});
});
// do other stuff with mdb
You can also look into using Mongoose as you mentioned middleware.
The connection is only opened once (on the global scope) and then you can use it throughout the app.

How to implement callbacks on AWS RDS PostgreSQL using node.js

I'm trying to implement a call back on NodeJS EC2 server that's interacting with AWS RDS Postgresql. I'm not quite sure how it's done. There seems to be a EventEmitter method within AWS-SDK's RDS module. It's designed for all RDS instance types like MySQL, Aurora, etc. Not specifically for postgres. All I'm trying to do is to get some kind of callback after an INSERT or DELETE query.
It is not specific if your postgres is RDS or standalone on EC2.
You will need
var pg = require('pg');
var dbe={"result":null};
function Q(sqlQuery,callback) {
/* async, vulnerable, simple */
var conString = "postgres://"+dbUser+":"+dbPass+"#"+dbHost+":"+dbPort+"/"+dbName+"?ssl=true";
pg.connect(conString, function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
client.query(sqlQuery, function(err, result) {
done();//call `done()` to release the client back to the pool
if(err) {
return console.error('error running query', err);
}
dbe.result = result;
//console.log(JSON.parse(result.setEncoding('utf8');));
callback();
});
});
}
And calling
var res = Q('select now()', function(a) {console.log(dbe.result)});
or similar - I don't have a playground to test atm

How to install NodeJS + MongoDB on ec2 Amazon server

I don't have much knowledge about mongo and NodeJS, and also about server set up so I might be asking something basic.
I'm trying to install MongoDB and NodeJS for school project.
In order to do so I registered to Amazon EC2 server and implemented an instance according to some tutorials I've found on line.
Using MongoDB wiki, I've installed Mongo on the server and using another Tutorial I installed NodeJS.
Just to be super clear, please see below picture who's showing the directory and MongoDB server listening:
http://s23.postimg.org/k02f747m2/mongo_Dir.jpg
After I've done that I'm trying to start using the server, I've created a simple file using the following code:
var mongodb = require('mongodb');
var server = new mongodb.Server('127.0.0.1', 27017, {});
var client = new mongodb.Db('exampledb', server, {w: 1});
client.open(function(err) {
if (err) throw err;
client.collection('students', function(err, collection) {
if (err) throw err;
collection.insert(
{
"name": "Noam",
"year": "2012."
},
{safe: true},
function(err, documents) {
if (err) throw err;
console.log('Document ID is: ' + documents[0]._id);
}
);
});
});
Now I tried to run the file and received the following error
http://s30.postimg.org/sqplfazlt/eror.jpg
Any help?

How to init native Mongo in NodeJS with at Sign in password

I am trying to figure out how to connect to my mongodb db using the native node mongo driver and I have two issues:
My password contains an # sign making it break the normal user:pass#host connection string format
How do I list databases from what I have below?
Any ideas on how to address this?
Here is an attempt which does not work:
var Mongo = require('mongodb');
var server = new Mongo.Server('mongodb://myhost', 27017);
var db = new Mongo.Db('test', server);
db.open(function(err, db) {
console.log(err); //unable to connect
});
For future readers, I was able to resolve this with the connection option uri_decode_auth. You will need to encodeURIComponent(password) before embedding it in the connection string.
Here's a complete working example:
MongoClient.connect(connection, { uri_decode_auth: true }, function(err, db) {
if(err) {
return cb(err);
}
db.admin().listDatabases(function(err, dbs) {
console.log(dbs);
});
});
As mentioned on this answer:
The solution is to replace # with %40
I tested with the C# driver and it works like a charm.

Resources